I need to generate some 5x6 matrices in MATLAB. They need to consist of randomly generated integers in the range 1-6, however, an integer cannot occur more than once in a particular row or column.
Here is the script I am currently using to generate random 5x6 matrices:
mat=zeros(5,6);
rows=5;
columns=6;
for i=1:rows
for j=1:columns
mat(i,j)=round(rand*(high-low)+low);
end
end
disp(mat)
But I don't know how to insert the rule about repeats into this.
I'm sure this is a relatively simple problem but I'm very new to MATLAB and haven't been able to generate something that satisfies these conditions. I'd be greatful for any assistance anyone can give.
Don't try to fill the matrix with completely random ints all at once. The likelihood of that being a valid puzzle grid is vanishingly low.
Instead, use the same method as used by Sudoku generators - start with a blank matrix and fill in elements one at a time, as restricted by your rules.
Where you have more than one choice for the entry, pick one of them at random.
You might progress something like this (4x4 example for brevity - allowable numbers 1-4)
Pick first number by dice roll: 3.
Pick second number from list of allowable numbers: [1, 2, 4].
Pick third number from list of allowable numbers, [1, 4]:
And so on.
If your "list of allowable numbers" at some insertion step is an empty set, then your matrix can't be salvaged and you may need to start again.
Also a 10x10 matrix with 5 unique integers is clearly impossible - insert some logic to test for this trivial error case.
Edit: Since it's not homework in the traditional sense, and since it was an interesting problem....
Invocation and output are like:
Don't say I never gave you nothing. ;)
Here's another way of doing it:
Start off with a known valid solution, say this one:
Then swap rows and columns at random. You can prove that each swap preserves the "no-repeats" property in each row and column.
Say you swap row 1 and row 2. You haven't changed the contents of the rows, so the "no repeats in each row" property remains true. Similarly, you haven't changed the contents of any of the columns - just the ordering - so the "no repeats in each column" property also remains true.
Here is what I came up with:
Example usage:
I'm not sure this is probably "as random" as the other way - but this way is fast and it doesn't need any logic to detect a failure (because it will (provably) always produce a correct result.)
Try this: