Random Latin squares: Difference between revisions
Content deleted Content added
SqrtNegInf (talk | contribs) Added Perl example |
|||
Line 619: | Line 619: | ||
0 1 4 2 3 |
0 1 4 2 3 |
||
</pre> |
</pre> |
||
=={{header|Kotlin}}== |
|||
{{trans|Go}} |
|||
<lang scala>typealias matrix = MutableList<MutableList<Int>> |
|||
fun printSquare(latin: matrix) { |
|||
for (row in latin) { |
|||
println(row) |
|||
} |
|||
println() |
|||
} |
|||
fun latinSquare(n: Int) { |
|||
if (n <= 0) { |
|||
println("[]") |
|||
return |
|||
} |
|||
val latin = MutableList(n) { MutableList(n) { it } } |
|||
// first row |
|||
latin[0].shuffle() |
|||
// middle row(s) |
|||
for (i in 1 until n - 1) { |
|||
var shuffled = false |
|||
shuffling@ |
|||
while (!shuffled) { |
|||
latin[i].shuffle() |
|||
for (k in 0 until i) { |
|||
for (j in 0 until n) { |
|||
if (latin[k][j] == latin[i][j]) { |
|||
continue@shuffling |
|||
} |
|||
} |
|||
} |
|||
shuffled = true |
|||
} |
|||
} |
|||
// last row |
|||
for (j in 0 until n) { |
|||
val used = MutableList(n) { false } |
|||
for (i in 0 until n - 1) { |
|||
used[latin[i][j]] = true |
|||
} |
|||
for (k in 0 until n) { |
|||
if (!used[k]) { |
|||
latin[n - 1][j] = k |
|||
break |
|||
} |
|||
} |
|||
} |
|||
printSquare(latin) |
|||
} |
|||
fun main() { |
|||
latinSquare(5) |
|||
latinSquare(5) |
|||
latinSquare(10) // for good measure |
|||
}</lang> |
|||
{{out}} |
|||
<pre>[4, 1, 2, 3, 0] |
|||
[1, 3, 0, 2, 4] |
|||
[3, 2, 4, 0, 1] |
|||
[0, 4, 3, 1, 2] |
|||
[2, 0, 1, 4, 3] |
|||
[2, 0, 3, 1, 4] |
|||
[0, 4, 1, 3, 2] |
|||
[1, 3, 2, 4, 0] |
|||
[3, 2, 4, 0, 1] |
|||
[4, 1, 0, 2, 3] |
|||
[7, 8, 4, 6, 5, 2, 9, 3, 1, 0] |
|||
[1, 5, 8, 2, 3, 0, 7, 9, 4, 6] |
|||
[6, 9, 5, 8, 7, 1, 3, 4, 0, 2] |
|||
[0, 6, 9, 4, 8, 3, 1, 2, 7, 5] |
|||
[4, 1, 3, 0, 6, 5, 8, 7, 2, 9] |
|||
[5, 0, 1, 7, 9, 4, 2, 6, 3, 8] |
|||
[2, 3, 6, 9, 4, 7, 0, 8, 5, 1] |
|||
[3, 7, 2, 5, 0, 9, 6, 1, 8, 4] |
|||
[8, 2, 0, 3, 1, 6, 4, 5, 9, 7] |
|||
[9, 4, 7, 1, 2, 8, 5, 0, 6, 3]</pre> |
|||
=={{header|M2000 Interpreter}}== |
=={{header|M2000 Interpreter}}== |
||
===Easy Way=== |
===Easy Way=== |