A Latin square of size n is an arrangement of n symbols in an n-by-n square in such a way that each row and column has each symbol appearing exactly once.

A randomised Latin square generates random configurations of the symbols for any given n.

Example n=4 randomised Latin square

0 2 3 1
2 1 0 3
3 0 1 2
1 3 2 0
Task

 Create a function/routine/procedure/method/... that given n generates a randomised Latin square of size n.
 Use the function to generate and show here, two randomly generated squares of size 5.
Note
 
Strict Uniformity in the random generation is a hard problem and not a requirement of the task.

Reference

 Wikipedia: Latin square
 OEIS: A002860


 
Module FastLatinSquare {
	n=5
	For k=1 To 2
		latin()
	Next
	n=40
	latin()
	Sub latin()
		Local i,a, a(1 To n), b, k
		Profiler
		flush
		Print "latin square ";n;" by ";n
		For i=1 To n
			Push i
		Next i
		For i=1 To n div 2
			Shiftback random(2, n)
		Next i
		a=[]
		Push ! stack(a)
		a=array(a)  ' change a from stack to array
		For i=1 To n*10
			Shiftback random(2, n)
		Next i
		For i=0 To n-1
			Data number  ' rotate by one the stack items
			b=[]    ' move stack To b, leave empty stack
			a(a#val(i))=b
			Push ! stack(b)  ' Push from a copy of b all items To stack
		Next i
		flush
		For k=1 To  n div 2
			z=random(2, n)
			For i=1 To n
				a=a(i)
				stack a {
					shift z
				}
			Next
		Next
		For i=1 To n
			a=a(i)
			a(i)=array(a)  ' change To array from stack
		Next i
		For i=1 To n
			Print a(i)
		Next i
		Print TimeCount
	End Sub
}
FastLatinSquare