Skip to content

Instantly share code, notes, and snippets.

@qittu
Last active August 29, 2015 14:00
Show Gist options
  • Save qittu/11189703 to your computer and use it in GitHub Desktop.
Save qittu/11189703 to your computer and use it in GitHub Desktop.
ぶどうの房のパズル http://www2.oninet.ne.jp/mazra/math104.htm
# Python 2.7.5
#
# Usage:
# $ python puzzle_of_vine.py STEP_NUMBER
import sys
import math
argv = sys.argv
if len(argv) < 2: exit("Error")
if not argv[1].isdigit(): exit("Error")
if argv[1] == "0": exit()
def triangle_number(number):
return number * (number + 1) / 2
def sort_digits(steps, digits, step, grapes):
if len(digits) < 1:
print_vine(steps, grapes)
return
if triangle_number(step) == len(grapes):
step = step + 1
for i in digits:
if 1 < step and triangle_number(step - 1) < len(grapes):
if math.fabs(i - grapes[-1]) != grapes[-1 * step]:
continue
listed_grapes = list(grapes)
listed_grapes.append(i)
free_digits = list(digits)
free_digits.remove(i)
sort_digits(steps, free_digits, step, listed_grapes)
def print_vine(steps, grapes):
for i in range(steps, 0, -1):
print "".rjust(steps - i, " ") + " ".join(map(str, grapes[-1 * i:]))
del grapes[-1 * i:]
print "\n"
steps = int(argv[1])
digits = list(range(1, triangle_number(steps) + 1))
sort_digits(steps, digits, 1, [])
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment