Skip to content

Instantly share code, notes, and snippets.

@Wrzlprmft
Last active January 18, 2022 07:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Wrzlprmft/62de41ff34685a80d9ad9afa483b7faf to your computer and use it in GitHub Desktop.
Save Wrzlprmft/62de41ff34685a80d9ad9afa483b7faf to your computer and use it in GitHub Desktop.
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