Here solutions is array . I need to know why this code is written.Please help me.

solutionsMod = Mod[solutions, n];

For[j = 1, j <= Length@solutions, j++,
   For[i = 1, j <= Length@solution[[1]], i++,
       If[solutionsMod[[j, i]] == 0, solutionsMod[[i, i]] =n;

Export[Tostring[n] <> ".txt", solutionsMod, "CSV"];

original png image

  • 4
    $\begingroup$ Please, in the future, post copyable code, not images. $\endgroup$ – Henrik Schumacher Jan 5 '19 at 15:34
  • $\begingroup$ This is a math question and not relevant to the underlying software being used. $\endgroup$ – Daniel Lichtblau Jan 5 '19 at 16:17
  • $\begingroup$ @Daniel Lichtbau The need to use Mod[i,n,1] instead of Mod[i,n] is very common when indices have to go from 1..,n instead of 0..n-1, such as for list, vector, or array indices in Mathematica. $\endgroup$ – Somos Jan 5 '19 at 23:07
  • $\begingroup$ @Somos I realize that (it's something I sometimes need myself). It's still basically a question about math-- such need can arise in any programming language. $\endgroup$ – Daniel Lichtblau Jan 6 '19 at 15:05
  • $\begingroup$ @DanielLichtblau You have a point, but, still, it arises in the context of Mathematica and very few languages have the equivalent of Mod[i,n,k]. It would me more complicated to have to explain the question in MSE. $\endgroup$ – Somos Jan 6 '19 at 16:29

For me, the For-loop looks like a very obfuscated and inefficient way of computing

solutionMods = Mod[solutions, n, 1];
  • $\begingroup$ Why need to Mod[] in cases of array? $\endgroup$ – Cecelia Jan 5 '19 at 15:39
  • $\begingroup$ @Thuriya, that question is a bit unclear; did you not take the Mod[] of the solutions array yourself in your question? $\endgroup$ – J. M. will be back soon Jan 5 '19 at 15:42
  • $\begingroup$ @ThuriyaThwin "Why need to Mod[] in cases of array? " The someone who created the code wanted each value in the array(?) solutions modded by n but with result n in case of 0. As I neither know who wrote that nor the purpose, how should I tell? Really, your questions lack a lot of context. Please provide all relevant information (in the future). $\endgroup$ – Henrik Schumacher Jan 5 '19 at 15:56

The answer by Henrik Schumacher is brief and to the point. However, the user may actually want to use a modified version instead.

solutions = Mod[solutions, n] + 1;

The reason why is that in order to map 0..n-1 to 1..n in a contiguous way you need i -> i+1. The use of Mod[i, n, 1] only changes the mapping of 0 to n which is exactly what you want in order to fix an original mapping using Mod[i, n]. Thus, perhaps the best solution may be to fix the original code to use something like Mod[i, n] + 1 instead of Mod[i, n].


Not the answer you're looking for? Browse other questions tagged or ask your own question.