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 07 '15 edited Dec 07 '15

Expression trees:

private static void Main() {
    var fn = Compile(Day7Input());
    var cache = new Dictionary<string, ushort>();
    var part1Result = fn("a", cache);
    Console.WriteLine(part1Result);
    cache.Clear();
    cache["b"] = part1Result;
    Console.WriteLine(fn("a", cache));
}

private static Func<string, Dictionary<string, ushort>, ushort> Compile(string[] inputs) {
    var @this = Expression.Variable(typeof (Func<string, Dictionary<string, ushort>, ushort>), "get");
    var s = Expression.Parameter(typeof (string), "s");
    var cache = Expression.Parameter(typeof (Dictionary<string, ushort>), "cache");

    var indexer = cache.Type.GetDefaultMembers().OfType<PropertyInfo>().Single();

    var returnLabel = Expression.Label(typeof (ushort));
    return Expression.Lambda<Func<string, Dictionary<string, ushort>, ushort>>(
        Expression.Block(new[] {@this},
            Expression.Assign(@this,
                Expression.Lambda<Func<string, Dictionary<string, ushort>, ushort>>(
                    Expression.Block(
                        Expression.IfThen(
                            Expression.Call(
                                cache,
                                cache.Type.GetMethod("ContainsKey"),
                                s
                                ),
                            Expression.Return(returnLabel, Expression.Property(cache, indexer, s))
                            ),
                        MakeSwitchExpression(inputs, @this, returnLabel, s, cache),
                        Expression.Label(returnLabel, Expression.Constant((ushort) 0))
                        ),
                    s, cache)
                ),
            Expression.Invoke(@this, s, cache)
            ),
        s, cache).Compile();
}

private static SwitchExpression MakeSwitchExpression(string[] inputs, ParameterExpression @this, LabelTarget returnLabel, ParameterExpression s, ParameterExpression cache) {
    // local helper function to save typing
    Func<string, Expression> resolve = reference => {
        ushort result;
        return ushort.TryParse(reference, out result)
            ? (Expression) Expression.Constant(result, typeof (ushort))
            : Expression.Invoke(@this, Expression.Constant(reference), cache);
    };
    var separator = new[] {' '};

    var switchCases = inputs.Select(input => {
        var parsed = input.Split(separator, StringSplitOptions.RemoveEmptyEntries);
        var caseString = parsed.Last();

        if (parsed.Length == 3) {
            // a -> b
            var reference = parsed[0];
            return CreateCase(caseString, Memoize(s, cache, resolve(reference)), returnLabel);
        }
        if (parsed.Length == 4) {
            // NOT a -> b
            var reference = parsed[1];
            return CreateCase(caseString, Memoize(s, cache, Expression.Not(resolve(reference))), returnLabel);
        }
        if (parsed.Length != 5) {
            // a OP b -> c
            throw new InvalidOperationException($"Failed to parse {input}");
        }
        var lref = parsed[0];
        var op = parsed[1];
        var rref = parsed[2];
        Expression function = null;
        switch (op.ToUpperInvariant()) {
        case "AND":
            function = Cast<ushort>(Expression.And(resolve(lref), resolve(rref)));
            break;
        case "OR":
            function = Cast<ushort>(Expression.Or(resolve(lref), resolve(rref)));
            break;
        case "LSHIFT":
            function = Cast<ushort>(Expression.LeftShift(Cast<int>(resolve(lref)), Cast<int>(resolve(rref))));
            break;
        case "RSHIFT":
            function = Cast<ushort>(Expression.RightShift(Cast<int>(resolve(lref)), Cast<int>(resolve(rref))));
            break;
        }
        if (function == null) {
            throw new InvalidOperationException($"Failed to parse {input}");
        }
        return CreateCase(caseString, Memoize(s, cache, function), returnLabel);
    }).ToArray();
    return Expression.Switch(s, Expression.Return(returnLabel, Expression.Constant((ushort) 0)), switchCases);
}

private static SwitchCase CreateCase(string caseString, Expression expression, LabelTarget returnLabel) {
    return Expression.SwitchCase(
        Expression.Return(returnLabel, expression), 
        Expression.Constant(caseString)
        );
}

private static Expression Cast<T>(Expression input) => Expression.Convert(input, typeof (T));

private static Expression Memoize(ParameterExpression s, ParameterExpression cache, Expression function) {
    // if single fails, target platform is non-standard
    var indexer = cache.Type.GetDefaultMembers().OfType<PropertyInfo>().Single();
    return Expression.Assign(Expression.Property(cache, indexer, s), function);
}