Random Latin squares: Difference between revisions

Content added Content deleted
(Promote to full task status)
Line 1,558: Line 1,558:
14 1 9 6 10 5 11 3 16 2 4 13 12 15 8 7
14 1 9 6 10 5 11 3 16 2 4 13 12 15 8 7
</pre >
</pre >

=={{header|Nim}}==
{{trans|Kotlin}}
Not a straight translation of Kotlin version. There are many differences but the algorithm is the same.

Starting at n = 11, the execution time will be very variable as the program proceeds by trial and error. At least, the algorithm will be able to produce all the possible Latin squares but not in a uniform way.

<lang Nim>import random, sequtils, strutils

type LatinSquare = seq[seq[char]]

proc get[T](s: set[T]): T =
## Return the first element of a set.
for n in s:
return n

proc letterAt(n: Natural): char {.inline.} = chr(ord('A') - 1 + n)


proc latinSquare(n: Positive): LatinSquare =
result = newSeqWith(n, toSeq(letterAt(1)..letterAt(n)))
result[0].shuffle()

for row in 1..(n - 2):
var ok = false
while not ok:
block shuffling:
result[row].shuffle()
for prev in 0..<row:
for col in 0..<n:
if result[row][col] == result[prev][col]:
break shuffling
ok = true

for col in 0..<n:
var s = {letterAt(1)..letterAt(n)}
for row in 0..(n - 2):
s.excl result[row][col]
result[^1][col] = s.get()


proc `$`(s: LatinSquare): string =
let n = s.len
for row in 0..<n:
result.add s[row].join(" ") & '\n'


randomize()
echo latinSquare(5)
echo latinSquare(5)
echo latinSquare(10)</lang>

{{out}}
<pre>D A C E B
A D B C E
B E D A C
E C A B D
C B E D A

E C D A B
B A C E D
C B A D E
A D E B C
D E B C A

D I J B H F G E A C
H E C G A I F D B J
I J G A F E C B D H
C D H J E A I G F B
G B A F I H E C J D
B F D E J C H I G A
F C B H D G A J I E
A H E I B D J F C G
J A I C G B D H E F
E G F D C J B A H I</pre>


=={{header|Perl}}==
=={{header|Perl}}==