将n组1-n随机置于n*n的单元格中,使得每行,每列都是1-n的一个全排列
- Sub Perm()
- Dim n As Long, i As Long, j As Long, arr(), brr(), t As Long
- n = 20
- ReDim arr(n - 1, n - 1)
- ReDim brr(n - 1)
- For i = 0 To n ^ 2 - 1
- arr(i / n, i Mod n) = (i / n + i) Mod n + 1
- Next
- Randomize
- For i = n - 1 To 0 Step -1
- t = Int(Rnd * i + 1)
- For j = 0 To n - 1
- brr(j) = arr(j, t)
- Next
- For j = 0 To n - 1
- arr(j, t) = arr(j, i)
- arr(j, i) = brr(j)
- Next
- t = Int(Rnd * i + 1)
- For j = 0 To n - 1
- brr(j) = arr(t, j)
- Next
- For j = 0 To n - 1
- arr(t, j) = arr(i, j)
- arr(i, j) = brr(j)
- Next
- Next
- [a1].Resize(n, n) = arr
- End Sub
执行结果:
1 | 19 | 14 | 6 | 8 | 9 | 18 | 10 | 16 | 11 | 13 | 4 | 20 | 17 | 3 | 5 | 15 | 2 | 7 | 12 |
3 | 1 | 16 | 8 | 10 | 11 | 20 | 12 | 18 | 13 | 15 | 6 | 2 | 19 | 5 | 7 | 17 | 4 | 9 | 14 |
10 | 8 | 3 | 15 | 17 | 18 | 7 | 19 | 5 | 20 | 2 | 13 | 9 | 6 | 12 | 14 | 4 | 11 | 16 | 1 |
16 | 14 | 9 | 1 | 3 | 4 | 13 | 5 | 11 | 6 | 8 | 19 | 15 | 12 | 18 | 20 | 10 | 17 | 2 | 7 |
14 | 12 | 7 | 19 | 1 | 2 | 11 | 3 | 9 | 4 | 6 | 17 | 13 | 10 | 16 | 18 | 8 | 15 | 20 | 5 |
2 | 20 | 15 | 7 | 9 | 10 | 19 | 11 | 17 | 12 | 14 | 5 | 1 | 18 | 4 | 6 | 16 | 3 | 8 | 13 |
17 | 15 | 10 | 2 | 4 | 5 | 14 | 6 | 12 | 7 | 9 | 20 | 16 | 13 | 19 | 1 | 11 | 18 | 3 | 8 |
15 | 13 | 8 | 20 | 2 | 3 | 12 | 4 | 10 | 5 | 7 | 18 | 14 | 11 | 17 | 19 | 9 | 16 | 1 | 6 |
20 | 18 | 13 | 5 | 7 | 8 | 17 | 9 | 15 | 10 | 12 | 3 | 19 | 16 | 2 | 4 | 14 | 1 | 6 | 11 |
18 | 16 | 11 | 3 | 5 | 6 | 15 | 7 | 13 | 8 | 10 | 1 | 17 | 14 | 20 | 2 | 12 | 19 | 4 | 9 |
13 | 11 | 6 | 18 | 20 | 1 | 10 | 2 | 8 | 3 | 5 | 16 | 12 | 9 | 15 | 17 | 7 | 14 | 19 | 4 |
7 | 5 | 20 | 12 | 14 | 15 | 4 | 16 | 2 | 17 | 19 | 10 | 6 | 3 | 9 | 11 | 1 | 8 | 13 | 18 |
8 | 6 | 1 | 13 | 15 | 16 | 5 | 17 | 3 | 18 | 20 | 11 | 7 | 4 | 10 | 12 | 2 | 9 | 14 | 19 |
12 | 10 | 5 | 17 | 19 | 20 | 9 | 1 | 7 | 2 | 4 | 15 | 11 | 8 | 14 | 16 | 6 | 13 | 18 | 3 |
6 | 4 | 19 | 11 | 13 | 14 | 3 | 15 | 1 | 16 | 18 | 9 | 5 | 2 | 8 | 10 | 20 | 7 | 12 | 17 |
11 | 9 | 4 | 16 | 18 | 19 | 8 | 20 | 6 | 1 | 3 | 14 | 10 | 7 | 13 | 15 | 5 | 12 | 17 | 2 |
9 | 7 | 2 | 14 | 16 | 17 | 6 | 18 | 4 | 19 | 1 | 12 | 8 | 5 | 11 | 13 | 3 | 10 | 15 | 20 |
19 | 17 | 12 | 4 | 6 | 7 | 16 | 8 | 14 | 9 | 11 | 2 | 18 | 15 | 1 | 3 | 13 | 20 | 5 | 10 |
5 | 3 | 18 | 10 | 12 | 13 | 2 | 14 | 20 | 15 | 17 | 8 | 4 | 1 | 7 | 9 | 19 | 6 | 11 | 16 |
4 | 2 | 17 | 9 | 11 | 12 | 1 | 13 | 19 | 14 | 16 | 7 | 3 | 20 | 6 | 8 | 18 | 5 | 10 | 15 |