6
$\begingroup$

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?

$\endgroup$

4 Answers 4

8
$\begingroup$
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)$

$\endgroup$
2
  • $\begingroup$ This works slightly faster than Henrik's solution, thank you. $\endgroup$ Commented Dec 22, 2019 at 4:24
  • $\begingroup$ Replacing Table with ConstantArray is faster for large matrix.. $\endgroup$ Commented Dec 22, 2019 at 4:37
7
$\begingroup$
a = Flatten[ConstantArray[Range[9], 9]]; Partition[a[[PermutationList[RandomPermutation[9^2], 9^2]]], 9] 
$\endgroup$
2
  • $\begingroup$ Works well, thanks. $\endgroup$ Commented Dec 21, 2019 at 22:23
  • $\begingroup$ You're welcome. $\endgroup$ Commented Dec 21, 2019 at 22:24
3
$\begingroup$
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|>

$\endgroup$
1
$\begingroup$

This should be pretty fast:

Partition[RandomSample[Mod[Range[9^2], 9, 1]], 9] 
$\endgroup$

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.