Tuesday, March 20, 2012

Grid Walk

Challenge Description
There is a monkey which can walk around on a planar grid. The monkey can move one space at a time left, right, up or down. That is, from (x, y) the monkey can go to (x+1, y), (x-1, y), (x, y+1), and (x, y-1). Points where the sum of the digits of the absolute value of the x coordinate plus the sum of the digits of the absolute value of the y coordinate are lesser than or equal to 19 are accessible to the monkey. For example, the point (59, 79) is inaccessible because 5 + 9 + 7 + 9 = 30, which is greater than 19. Another example: the point (-5, -7) is accessible because abs(-5) + abs(-7) = 5 + 7 = 12, which is less than 19. How many points can the monkey access if it starts at (0, 0), including (0, 0) itself?

InputThere is no input for this program.

Output
Print out the how many points can the monkey access. (The number should be printed as an integer whole number eg.
if the answer is 10 (its not !!), print out 10, not 10.0 or 10.00 etc)

exist = []
point = {}

#make sure the sum of digit is less or equal than 19
def belowUpper(x, y):
    if x<0 or y<0:
        return False
    abs_x = str(abs(x))
    abs_y = str(abs(y))
    sum_x = 0
    sum_y = 0
    for c in abs_x:
        sum_x = sum_x + int(c)
    for c in abs_y:
        sum_y = sum_y + int(c)

    if sum_x + sum_y <= 19:
        return True



#check the point is valid or not
def addToList(x, y):
    if belowUpper(x+1, y):
        tmp = str(x+1) + " " + str(y)
        try:
            point[tmp]
        except:
            point[tmp] = 1
            exist.append([x+1, y])
        
        
    if belowUpper(x, y+1):
        tmp = str(x) + " " + str(y+1)
        try:
            point[tmp]
        except:
            point[tmp] = 1
            exist.append([x, y+1])




#remove overlap part when x = 0 or y = 0
def removeOverlap(x, y):
    total = 0
    xx = x
    yy = y
    while True:
        if belowUpper(xx, yy):
           total += 1
           xx += 1
        else:
            break

    return total
    

#main function
exist.append([0,0])

start = 0

while True:
    addToList(exist[start][0],exist[start][1])
    start+=1
    if start >= len(exist):
        break

over = removeOverlap(0, 0)

print (len(exist) - (over)) * 4 + 1