2015-12-12 - JSAbacusFramework.io
(original .ipynb)
Problem input is a json file. Part one involves finding the sum of the numbers in the structure. Part two involves the same sort of thing, but evaluating dictionary-type structures as zero if any node has a value "red".
import json puzzle_input_str = open("./puzzle_input/day12.txt").read() def node_sum(node, accumulator, string_handler): if type(node) == int: return node elif type(node) == dict: return accumulator([node_sum(node[key], accumulator, string_handler) for key in node]) elif type(node) == list: return sum([node_sum(n, accumulator, string_handler) for n in node if node_sum(n, accumulator, string_handler) != None]) elif type(node) == str: return string_handler(node) raise Error("Nope") def part_one(input_str): account_json = json.loads(input_str) return node_sum(account_json, sum, lambda _: 0) assert 6 == part_one('[1,2,3]') assert 6 == part_one('{"a":2,"b":4}') assert 3 == part_one('[[[3]]]') assert 3 == part_one('{"a":{"b":4},"c":-1}') assert 0 == part_one('{"a":[-1,1]}') assert 0 == part_one('[-1,{"a":1}]') assert 0 == part_one("[]") assert 0 == part_one("{}") print("part one:", part_one(puzzle_input_str))
part one: 156366
def red_string_handler(node): if node != "red": return 0 return None def sum_or_zero_red(collection): if None in collection: return 0 return sum(collection) def part_two(input_str): account_json = json.loads(input_str) return node_sum(account_json, sum_or_zero_red, red_string_handler) assert 6 == part_two('[1,2,3]') assert 4 == part_two('[1,{"c":"red","b":2},3]') assert 0 == part_two('{"d":"red","e":[1,2,3,4],"f":5}') assert 6 == part_two('[1,"red",5]') print("part two:", part_two(puzzle_input_str))
part two: 96852