#!/usr/bin/python3
# -*- coding: utf-8 -*-
'''
Triangle, square, pentagonal, hexagonal, heptagonal, and octagonal numbers are all figurate (polygonal) numbers and are generated by the following formulae:
Triangle	 	P3,n=n(n+1)/2	 	1, 3, 6, 10, 15, ...
Square	 	P4,n=n2	 	1, 4, 9, 16, 25, ...
Pentagonal	 	P5,n=n(3n−1)/2	 	1, 5, 12, 22, 35, ...
Hexagonal	 	P6,n=n(2n−1)	 	1, 6, 15, 28, 45, ...
Heptagonal	 	P7,n=n(5n−3)/2	 	1, 7, 18, 34, 55, ...
Octagonal	 	P8,n=n(3n−2)	 	1, 8, 21, 40, 65, ...


The ordered set of three 4-digit numbers: 8128, 2882, 8281, has three interesting properties.
The set is cyclic, in that the last two digits of each number is the first two digits of the next number (including the last number with the first).
Each polygonal type: triangle (P3,127=8128), square (P4,91=8281), and pentagonal (P5,44=2882), is represented by a different number in the set.
This is the only set of 4-digit numbers with this property.

Find the sum of the only ordered set of six cyclic 4-digit numbers for which each polygonal type: triangle, square, pentagonal, hexagonal, heptagonal, and octagonal, is represented by a different number in the set.
'''


import math

DEBUG = False
def d(args):
    global DEBUG
    if DEBUG:
      print(args)


def triangle(n):
  # several 4-digit numbers with same two upper digits
  return n*(n+1)//2
  
def square(n):
    # 2 4-digit numbers with same two upper digits
    return n*n

def pentagonal(n):
    return n*(3*n-1)//2

def hexagonal(n):
    return n*(2*n-1)
    
def heptagonal(n):
    return n*(5*n-3)//2

def octagonal(n):
    return n*(3*n-2)

def buildMap(f):
    i = 1
    r = {}
    while True:
      fn = f(i)
      i = i + 1
      if fn >= (10**4):
        return r
      if fn >= (10**3):
        idx = str(fn // 100)
        val = str(fn % 100)
        # skip numbers xx0x
        if len(val) == 2:
          if not idx in r:
            r[idx] = []
          r[idx].append(val)
          if len(r[idx]) > 1:
            d('dupe %s' % str(f))
    raise Exception("Unexpected end")

def selectNext(sel, T):
   last = sel[-1]

   if len(T) == 0 and last == sel[0]:
      return sel

   for i in range(len(T)):
     d('test row %i' %i)
     t = T[i]
     if last in t:
       d('found %s in %i' % (last,i))
       nxtList = t[last]
       for nxt in nxtList:
         selCurr = sel + [i, nxt]
         Tmt = T[:]
         del(Tmt[i])
         res = selectNext(selCurr, Tmt)
         if res:
           return res

   return None
  
def buildTable():
    
    F=[triangle, square, pentagonal, hexagonal, heptagonal, octagonal][::-1]
    T = []
    for f in F:
       T.append(buildMap(f))
    return T
      

   
def main():
    T=buildTable()
    for x in T:
       d(x)
       d('-'*60)

    T0 = T[0]
    T1 = T[1:]

    for start in T0:
       # for each start, there is only one end, because no 'dupe' message for octagonal
       sel = [start, 0,  T0[start][0]]
       d('test %s' % sel)
       res =  selectNext(sel, T1)
       if res:
        print (res)

        R = []
        for i in range(6):
          R.append(int(res[0] + res[2]))
          res = res [2:]
        print (sum(R))
 
        #exit()


if  __name__ =='__main__':main()

