October 20, 2023

Solution for Advent of Code 2015 - Day 12: JSAbacusFramework.io

Link to the puzzle text

Part 1

For this puzzle we have an JSON array and we need to sum up all the numbers in it.
First we parse our input into using the json.loads() function, so we can easily iterate handle it. The summing up is best done recursively, by starting at the root of the JSON. We then iterate over all children and have different cases. If the child node is a number, then we add it to the total sum. If it is a dict/list, then we recursively call the sum_json() function on the child node and add the result of the call.

def sum_json(tree):
child_sum = 0
for child in tree:
if isinstance(tree, dict):
child = tree[child]

if isinstance(child, dict):
child_sum += sum_json(child)
elif isinstance(child, list):
child_sum += sum_json(child)
elif isinstance(child, int):
child_sum += child
else:
pass
return child_sum

This was tested against the examples and resulted in the answer.

Part 2

For part 2, we have another requirement: If a child is a node and contains the string "red", the sum of this child is now 0. We can simply add this to our function with these two lines:

if child == "red" and isinstance(tree, dict):
return 0

No comments:

Post a Comment