Skip to content

Instantly share code, notes, and snippets.

@paulc
Created September 11, 2016 20:03
Show Gist options
  • Select an option

  • Save paulc/0c8b186d20fb14fdb9901a6554e1f66e to your computer and use it in GitHub Desktop.

Select an option

Save paulc/0c8b186d20fb14fdb9901a6554e1f66e to your computer and use it in GitHub Desktop.
Triangle Puzzle
import itertools
def triangle(base):
stack = [base]
while len(stack[-1])>1:
stack.append([abs(i-j) for i,j in zip(stack[-1],stack[-1][1:])])
return stack
def check(triangle):
return len(set(itertools.chain(*triangle))) == sum(range(len(triangle)+1))
def bases(layers):
max = sum(range(layers+1))
rev = set()
for c in itertools.combinations(range(2,max-1),layers-2):
for d in (max-1,1):
for p in itertools.permutations(c+(max,d)):
if p not in rev:
rev.add(tuple(reversed(p)))
if check(triangle(p)):
yield p
print("Count: ",len(rev))
def guess(layers):
for i in bases(layers):
print(triangle(i))
while True:
guess(int(input("Number of layers? ")))
## Number of layers? 2
## [(3, 2), [1]]
## [(3, 1), [2]]
## Count: 2
## Number of layers? 3
## [(2, 6, 5), [4, 1], [3]]
## [(6, 2, 5), [4, 3], [1]]
## [(4, 6, 1), [2, 5], [3]]
## [(4, 1, 6), [3, 5], [2]]
## Count: 18
## Number of layers? 4
## [(8, 3, 10, 9), [5, 7, 1], [2, 6], [4]]
## [(8, 10, 3, 9), [2, 7, 6], [5, 1], [4]]
## [(6, 10, 1, 8), [4, 9, 7], [5, 2], [3]]
## [(6, 1, 10, 8), [5, 9, 2], [4, 7], [3]]
## Count: 504
## Number of layers? 5
## [(6, 14, 15, 3, 13), [8, 1, 12, 10], [7, 11, 2], [4, 9], [5]]
## Count: 26400
## Number of layers? 6
## Count: 2203200
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment