# https://projecteuler.net/problem=61
from projecteuler.NumberProperties import nth_polygonal

polygonal_numbers = [[], [], [], [], [], []]

# creates a list of every 4-digit s-gonal number
for n in range(1, 150):
    for i, s in enumerate(range(3, 9)):
        nth_poly = nth_polygonal(n, s)
        if 1000 <= nth_poly < 10000:
            # originally, I thought each number had to be uniquely s-gonal
            # if not any([is_polygonal(n, x) for x in range(3, 9) if x != s]):
            polygonal_numbers[i].append(str(nth_poly))


# finds the numbers in polygonal_numbers that are cyclic.
# unused_nums are the indexes of polygonal_numbers
# that a number still needs to be found for
def cyclic_sum(current_num, unused_nums):
    if len(unused_nums) == 0 and current_num[:2] == current_num[-2:]:
        return sum([int(current_num[idx:idx+4]) for idx in range(0,len(current_num)-2,2)])
    for idx in unused_nums:
        for n in polygonal_numbers[idx]:
            if n[:2] == current_num[-2:]:
                ans = cyclic_sum(current_num + n[-2:],
                                 [x for x in unused_nums if x != idx])
                if ans is not None:
                    return ans
    return None

answer = None
idx = 0
while answer is None:
    answer = cyclic_sum(polygonal_numbers[5][idx], [0, 1, 2, 3, 4])
    idx += 1
print(answer)
