# Generating random matrices with constraints

I would like to generate random $$9\times9$$ matrices which contain only the digits $$1$$ through $$9$$ (inclusive), each digit appearing exactly $$9$$ times.

How can I do so using Mathematica?

Partition[RandomSample[Flatten@Table[Range@9, 9]], 9] // MatrixForm


$$\left( \begin{array}{ccccccccc} 7 & 2 & 5 & 3 & 6 & 5 & 8 & 5 & 2 \\ 7 & 1 & 1 & 1 & 4 & 7 & 5 & 8 & 6 \\ 6 & 3 & 9 & 3 & 2 & 1 & 8 & 3 & 6 \\ 3 & 4 & 5 & 7 & 2 & 6 & 6 & 9 & 4 \\ 2 & 4 & 9 & 1 & 8 & 9 & 5 & 7 & 4 \\ 4 & 4 & 9 & 9 & 2 & 8 & 5 & 8 & 3 \\ 8 & 9 & 1 & 7 & 7 & 9 & 4 & 3 & 1 \\ 3 & 2 & 6 & 2 & 6 & 4 & 1 & 7 & 6 \\ 2 & 1 & 7 & 8 & 5 & 9 & 5 & 8 & 3 \\ \end{array} \right)$$

• This works slightly faster than Henrik's solution, thank you. Dec 22, 2019 at 4:24
• Replacing Table with ConstantArray is faster for large matrix.. Dec 22, 2019 at 4:37
a = Flatten[ConstantArray[Range[9], 9]];
Partition[a[[PermutationList[RandomPermutation[9^2], 9^2]]], 9]

• Works well, thanks. Dec 21, 2019 at 22:23
• You're welcome. Dec 21, 2019 at 22:24
ClearAll[f]
f = ArrayReshape[RandomSample[Join @@ ConstantArray[Range@#, #]], {#, #}] &;

SeedRandom[1]
f @ 9 // MatrixForm // TeXForm


$$\left( \begin{array}{ccccccccc} 9 & 6 & 1 & 5 & 4 & 3 & 6 & 6 & 7 \\ 7 & 5 & 2 & 4 & 4 & 8 & 9 & 3 & 3 \\ 4 & 9 & 7 & 7 & 8 & 2 & 4 & 3 & 4 \\ 5 & 5 & 7 & 8 & 2 & 8 & 6 & 1 & 1 \\ 3 & 2 & 9 & 8 & 3 & 9 & 5 & 5 & 4 \\ 3 & 2 & 9 & 9 & 1 & 8 & 6 & 5 & 5 \\ 8 & 9 & 6 & 1 & 6 & 9 & 7 & 7 & 8 \\ 1 & 3 & 2 & 4 & 4 & 7 & 3 & 6 & 2 \\ 7 & 1 & 6 & 5 & 8 & 1 & 2 & 1 & 2 \\ \end{array} \right)$$

KeySort @ Counts[Flatten @ f @ 9]


<|1 -> 9, 2 -> 9, 3 -> 9, 4 -> 9, 5 -> 9, 6 -> 9, 7 -> 9, 8 -> 9, 9 -> 9|>

This should be pretty fast:

Partition[RandomSample[Mod[Range[9^2], 9, 1]], 9]