Latin Square is an nxn array filled with n different symbols, each occurring exactly once in each row and exactly once in each column (like sudoku). An example of Latin Square:
1 2 3
2 3 1
3 1 2
This is what I've tried, but it is still not all distinct
grid = []
temp = []
block = [[1,2,3],
[2,3,1],
[3,1,2]]
perm = permutations(block)
for i in perm: #row permutations
temp.extend(i)
if len(temp)==3:
grid.extend([temp])
temp = []
for perm in zip(permutations(block[0]), permutations(block[1]), permutations(block[2])): #column permutations
temp.extend([perm])
for i in range(len(temp)): #convert to list
temp[i] = list(temp[i])
for j in range(len(temp[0])):
temp[i][j] = list(temp[i][j])
grid.extend(temp)
for i in grid:
for j in i:
print(j)
print()
Output is:
[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[2, 3, 1]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
[3, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[2, 3, 1]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[1, 2, 3]
[3, 2, 1]
[2, 1, 3]
[1, 3, 2]
[1, 3, 2]
[3, 2, 1]
[2, 1, 3]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[2, 3, 1]
[1, 2, 3]
[3, 1, 2]
[2, 1, 3]
[1, 3, 2]
[3, 2, 1]
The result is supposed to be like this (order doesn't matter): Latin Square
[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[1, 3, 2]
[2, 1, 3]
[3, 2, 1]
[1, 3, 2]
[3, 2, 1]
[2, 1, 3]
[2, 1, 3]
[1, 3, 2]
[3, 2, 1]
[2, 1, 3]
[3, 2, 1]
[1, 3, 2]
[2, 3, 1]
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
[3, 2, 1]
[1, 3, 2]
[2, 1, 3]
[3, 2, 1]
[2, 1, 3]
[1, 3, 2]
[3, 1, 2]
[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
[2, 3, 1]
[1, 2, 3]
You can use recursion with a generator:
def row(n, r, c = []):
if len(c) == n:
yield c
for i in range(1, n+1):
if i not in c and i not in r[len(c)]:
yield from row(n, r, c+[i])
def to_latin(n, c = []):
if len(c) == n:
yield c
else:
for i in row(n, [[]]*n if not c else list(zip(*c))):
yield from to_latin(n, c+[i])
for i in to_latin(3):
for b in i:
print(b)
print('-'*9)
Output:
[1, 2, 3]
[2, 3, 1]
[3, 1, 2]
---------
[1, 2, 3]
[3, 1, 2]
[2, 3, 1]
---------
[1, 3, 2]
[2, 1, 3]
[3, 2, 1]
---------
[1, 3, 2]
[3, 2, 1]
[2, 1, 3]
---------
[2, 1, 3]
[1, 3, 2]
[3, 2, 1]
---------
[2, 1, 3]
[3, 2, 1]
[1, 3, 2]
---------
[2, 3, 1]
[1, 2, 3]
[3, 1, 2]
---------
[2, 3, 1]
[3, 1, 2]
[1, 2, 3]
---------
[3, 1, 2]
[1, 2, 3]
[2, 3, 1]
---------
[3, 1, 2]
[2, 3, 1]
[1, 2, 3]
---------
[3, 2, 1]
[1, 3, 2]
[2, 1, 3]
---------
[3, 2, 1]
[2, 1, 3]
[1, 3, 2]
---------
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.