Project Euler #90: Cube digit pairs

  • + 0 comments

    I did not find this easy. Very tedious or maybe I didn't discover the "trick." This leads to frustration and diminished enjoyment. That's why I hope this helps someone and they can improve on this solution (and share their discovery with all). HackerRank Project Eulrer 90

    from itertools import combinations
    can = lambda d, x: x in d or (x in [6,9] and (6 in d or 9 in d))
    N,M = map(int,input().split())
    sq = [[int(x) for x in f"{i*i:0{M}d}"] for i in range(1, N+1)]
    def check_pair(d1, d2, cache={}):
        key = (d1, d2)
        if key not in cache:
            cache[key] = all(can(d1, s[0]) and can(d2, s[1]) or 
                             can(d1, s[1]) and can(d2, s[0]) for s in sq)
        return cache[key]
    
    def PE90(n, m):
        dice = list(combinations(range(10), 6))
        
        if m == 1:
            req = {s[0] for s in sq}
            return sum(all(can(d, x) for x in req) for d in dice)
            
        if m == 2:
            return sum(check_pair(dice[i], dice[j]) 
                      for i in range(len(dice)) for j in range(i, len(dice)))
        
        return sum(all(any(can(dice[p[0]], s[0]) and can(dice[p[1]], s[1]) 
                  and can(dice[p[2]], s[2]) for p in ((i,j,k), (i,k,j), (j,i,k),
                  (j,k,i), (k,i,j), (k,j,i))) for s in sq)
                  for i in range(len(dice)) 
                  for j in range(i, len(dice))
                  for k in range(j, len(dice)))
    
    print(PE90(N,M))