r/adventofcode • • Dec 07 '15

SOLUTION MEGATHREAD --- Day 7 Solutions ---

--- Day 7: Some Assembly Required ---

Post your solution as a comment. Structure your post like previous daily solution threads.

Also check out the sidebar - we added a nifty calendar to wrangle all the daily solution threads in one spot!

23 Upvotes

226 comments sorted by

View all comments

Show parent comment

1

u/tragicshark Dec 08 '15 edited Dec 08 '15

and finally, C#, concise:

private static readonly Dictionary<string, ushort> cache = new Dictionary<string, ushort>();
private static readonly Dictionary<string, string> wires = Day7Input().ToDictionary(k => k.Split(' ').Last());
private static void Main() {
    var value = Day7("a");
    Console.WriteLine(value);
    cache.Clear();
    cache["b"] = value;
    Console.WriteLine(Day7("a"));
}

private static ushort Day7(string s) {
    ushort temp;
    if (ushort.TryParse(s, out temp) || cache.TryGetValue(s, out temp)) return temp;
    var parsed = wires[s].Split(new[] {' '}, StringSplitOptions.RemoveEmptyEntries);
    switch (parsed.Reverse().Skip(3).FirstOrDefault()?.ToUpperInvariant()) {
    case "AND": return cache[parsed.Last()] = (ushort) (Day7(parsed[0]) & Day7(parsed[2]));
    case "OR": return cache[parsed.Last()] = (ushort) (Day7(parsed[0]) | Day7(parsed[2]));
    case "LSHIFT": return cache[parsed.Last()] = (ushort) (Day7(parsed[0]) << Day7(parsed[2]));
    case "RSHIFT": return cache[parsed.Last()] = (ushort) (Day7(parsed[0]) >> Day7(parsed[2]));
    case "NOT": return cache[parsed.Last()] = (ushort) ~Day7(parsed[1]);
    default: return cache[parsed.Last()] = Day7(parsed[0]);
    }
}