01020304050607080910111213141516171819202122232425

Advent of Code

2018/8

Memory Maneuver

in C#

by encse

The sleigh is much easier to pull than you'd expect for something its weight. Unfortunately, neither you nor the Elves know which way the North Pole is from here.

You check your wrist device for anything that might help. It seems to have some kind of navigation system! Activating the navigation system produces more bad news: "Failed to start navigation system. Could not read software license file."

Read the full puzzle.

using System;
using System.Linq;

namespace AdventOfCode.Y2018.Day08;

[ProblemName("Memory Maneuver")]
class Solution : Solver {

    public object PartOne(string input) =>
        Parse(input).fold(0, (cur, node) => cur + node.metadata.Sum());
    

    public object PartTwo(string input) {
        return Parse(input).value();
    }

    Node Parse(string input) {
        var nums = input.Split(" ").Select(int.Parse).GetEnumerator();
        Func<int> next = () => {
            nums.MoveNext();
            return nums.Current;
        };

        Func<Node> read = null;
        read = () => {
            var node = new Node() {
                children = new Node[next()],
                metadata = new int[next()]
            };
            for (var i = 0; i < node.children.Length; i++) {
                node.children[i] = read();
            }
            for (var i = 0; i < node.metadata.Length; i++) {
                node.metadata[i] = next();
            }
            return node;
        };
        return read();
    }


}

class Node {
    public Node[] children;
    public int[] metadata;
    public T fold<T>(T seed, Func<T, Node, T> aggregate) {
        return children.Aggregate(aggregate(seed, this), (cur, child) => child.fold(cur, aggregate));
    }

    public int value() {
        if(children.Length == 0){
            return metadata.Sum();
        }

        var res = 0;
        foreach(var i in metadata){
            if(i >= 1 && i <= children.Length){
                res += children[i-1].value();
            }
        }
        return res;
    }
}

Please ☆ my repo if you like it!

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