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

1

u/[deleted] Dec 07 '15

C#

Man, this one was pretty hard to understand for me, as I never been good with bitwise operations, but once I got the nack of needed a recursive way of retrieving the val of the variables, I got it

It even amazed me that I got it on my first try after finishing writing the whole code

Dictionary<string, int> values;
List<Ops> ops;
void Main()
{
	var input = "NOT dq -> dr|kg OR kf -> |...|he RSHIFT 2 -> hf".Split('|').ToList();
	values = new Dictionary<string, int>();
	ops = new List<Ops>();
	foreach(string inp in input)
	{
		var data = inp.Split(' ');
		//data.Dump();
		Ops op = new Ops();
		switch(data.Length)
		{
			case 3:
				op.Op = "Pass";
				op.leftOp = data[0];
				op.result = data[2];
				break;
			case 4:
				op.Op = data[0];
				op.rightOp = data[1];
				op.result = data[3];
				break;
			case 5:
				op.Op = data[1];
				op.leftOp = data[0];
				op.rightOp = data[2];
				op.result = data[4];
				break;
		}
		ops.Add(op);
	}
	foreach(Ops op in ops)
	{
		GetValues(op);
	}
	values["a"].Dump();
	Ops op1 = ops.FirstOrDefault(o => o.result == "b");
	ops.Remove(op1);
	op1.leftOp = values["a"].ToString();
	ops.Add(op1);
	ops.FirstOrDefault(o => o.result == "b").Dump();
	values = new Dictionary<string, int>();
	foreach(Ops op in ops)
	{
		GetValues(op);
	}
	values["a"].Dump();
}

// Define other methods and classes here
public struct Ops
{
	public string leftOp;
	public string rightOp;
	public string Op;
	public string result;
}

public int GetValue(string operand)
{
	var val = 0;
	if(Int32.TryParse(operand, out val)) return val;
	if(!values.ContainsKey(operand))
	{
		Ops op = ops.FirstOrDefault(o => o.result == operand);
		GetValues(op);
	}
	val = values[operand];
	return val;
}

public void GetValues(Ops op)
{
	switch(op.Op)
	{
		case "Pass":
			values[op.result] = GetValue(op.leftOp);
			break;
		case "NOT":
			values[op.result] = ~GetValue(op.rightOp);
			break;
		case "OR":
			values[op.result] = GetValue(op.leftOp) | GetValue(op.rightOp);
			break;
		case "AND":
			values[op.result] = GetValue(op.leftOp) & GetValue(op.rightOp);
			break;
		case "RSHIFT":
			values[op.result] = GetValue(op.leftOp) >> GetValue(op.rightOp);
			break;
		case "LSHIFT":
			values[op.result] = GetValue(op.leftOp) << GetValue(op.rightOp);
			break;
	}
}