Magic Trick, Qualification Round 2014.
Just as a reminder, all the Google Code Jam code and solutions I’m posting are based off of the template code I posted last year. It handles all the homework of reading and writing files properly and allows me to simply focus on solving the problem. I’ll generally only post the solve_case function and leave the rest to you.
As the first problem in the Qualification Round, this problem is more a test of basic coding ability than algorithm design. We’re given two 4 by 4 arrays and a row is chosen from each of them. The number of interest is supposed to be found in each of the chosen rows of the two arrays. So we want to find all numbers that are in both rows. We can do this quite easily using Python sets, although be careful of the indexing change from the row numbers we’re given (1 to 4) and the way Python indexes arrays (0 to 3). Once we have our list of potential numbers, then if there’s exactly one, that must be the one we want. If there’s more than two, the magician didn’t choose the arrays properly, and if there’s none, then the volunteer must be cheating.
def solve_case(case): ans1, grid1, ans2, grid2 = case valid = set(grid1[ans1-1]) & set(grid2[ans2-1]) if len(valid) == 1: return valid.pop() elif len(valid) > 1: return "Bad magician!" else: return "Volunteer cheated!"