Last active
January 18, 2022 07:15
-
-
Save Wrzlprmft/62de41ff34685a80d9ad9afa483b7faf to your computer and use it in GitHub Desktop.
Permutations Puzzle (https://puzzling.stackexchange.com/q/114452/5286)
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import numpy as np | |
n = 6 | |
m = 2*(n-1) | |
maximum = (m*(m+1))//2 | |
target = set(range(1,maximum)) | |
def explore(permutations): | |
sums = [ sum(p) for p in permutations ] | |
next_num = max(sums) + 1 | |
# If any row is too far behind: | |
if any(summe+m<next_num for summe in sums): | |
return | |
# If finished: | |
if next_num == maximum: | |
sums = { | |
x | |
for p in permutations | |
for x in np.cumsum(p) | |
} | |
assert(sums) == target | |
print(permutations) | |
for i,p in enumerate(permutations): | |
# Try generating the next number in the i-th row. | |
gap = next_num-sum(p) | |
if (1<=gap<=m) and (gap not in p): | |
permutations[i].append(next_num-sum(p)) | |
explore(permutations) | |
permutations[i].pop() | |
# Avoid redundant solutions by exploring first empty row only: | |
if not p: break | |
start = [[1]] + [ [] for _ in range(1,n) ] | |
explore(start) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment