01020304050607080910111213141516171819202122232425

Advent of Code

2015/12

JSAbacusFramework.io

in C#

by encse

Santa's Accounting-Elves need help balancing the books after a recent order. Unfortunately, their accounting software uses a peculiar storage format. That's where you come in.

They have a JSON document which contains a variety of things: arrays ([1,2,3]), objects ({"a":1, "b":2}), numbers, and strings. Your first job is to simply find all of the numbers throughout the document and add them together.

Read the full puzzle.

using System.Linq;
using System.Text.Json;

namespace AdventOfCode.Y2015.Day12;

[ProblemName("JSAbacusFramework.io")]
class Solution : Solver {

    public object PartOne(string input) => Solve(input, false);
    public object PartTwo(string input) => Solve(input, true);

    int Solve(string input, bool skipRed) {
        int Traverse(JsonElement t) {
            return t.ValueKind switch
            {
                JsonValueKind.Object when skipRed && t.EnumerateObject().Any(
                    p => p.Value.ValueKind == JsonValueKind.String && p.Value.GetString() == "red") => 0,
                JsonValueKind.Object => t.EnumerateObject().Select(p => Traverse(p.Value)).Sum(),
                JsonValueKind.Array => t.EnumerateArray().Select(Traverse).Sum(),
                JsonValueKind.Number => t.GetInt32(),
                _ => 0
            };
        }

        return Traverse(JsonDocument.Parse(input).RootElement);
    }
}

Please ☆ my repo if you like it!

© 2025 Advent of Code is a registered trademark in the US Images provided by Bing image creator