samedi 9 septembre 2023

Repeatedly using randperm until a standard is met always gives duplicate results on two consecutive runs

We have in Matlab the magic function, which generates a magic square. However, it always gives the same square while there can be multiple possible magic squares for a given dimension.

Now, I want to generate randomly a magic square of a given dimension, and I have a piece of code here:

while true
    nums = randperm(9);
    A = reshape(nums, 3, 3);
    if all(sum(A, 1) == 15) && all(sum(A, 2) == 15) && sum(diag(A)) == 15 && sum(diag(fliplr(A))) == 15
        break;
    end
end
disp(A);

It works almost fine. It generates the magic square well enough. However, on consecutive runs it gives me the same matrix:

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     1     8
     7     5     3
     2     9     4

>> ranMagic
     6     1     8
     7     5     3
     2     9     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     2     9     4
     7     5     3
     6     1     8

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     6     7     2
     1     5     9
     8     3     4

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

>> ranMagic
     8     1     6
     3     5     7
     4     9     2

Notice how the first two matrices are the same, then the third and forth, then the fifth and sixth... While it is true that 3D magic squares are scarce in number, with only 8 possible alternatives, this strikes me more than a mere coincidence. How come this happens?




Aucun commentaire:

Enregistrer un commentaire