Skip to content

Instantly share code, notes, and snippets.

@JakeKalkman
Created May 24, 2019 17:19
Show Gist options
  • Save JakeKalkman/dcb41ff840f6f98b04d9c6829094007e to your computer and use it in GitHub Desktop.
Save JakeKalkman/dcb41ff840f6f98b04d9c6829094007e to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
// Intructions are formatted as "b inc 5 if a > 1"
namespace AoC8
{
public class Instruction
{
public string VariableToModify { get; private set; }
public string PlusOrMinus { get; private set; }
public int ValueToModifyVariableBy { get; private set; }
public string VariableToEvaluate { get; private set; }
public Dictionary<string,int> VariableStorage { get; private set; }
public string StringOperand { get; private set; }
public int ConditionalValue { get; private set; }
public Instruction(string[] instructionStringSplit,Dictionary<string,int> variableStorage)
{
VariableToModify = instructionStringSplit[0];
PlusOrMinus = instructionStringSplit[1];
ValueToModifyVariableBy = Int32.Parse(instructionStringSplit[2]);
VariableStorage = variableStorage;
VariableToEvaluate = instructionStringSplit[4];
StringOperand = instructionStringSplit[5];
ConditionalValue = Int32.Parse(instructionStringSplit[6]);
CheckIfVariableExistsInDictionary(VariableToEvaluate);
CheckIfVariableExistsInDictionary(VariableToModify);
CheckIfVariableExistsInDictionary("Max");
}
public static Boolean Operator(string logic, int x, int y)
{
switch (logic)
{
case ">": return x > y;
case "<": return x < y;
case "==": return x == y;
case "!=": return x != y;
case "<=": return x <= y;
case ">=": return x >= y;
default: throw new Exception("invalid logic");
}
}
public void CheckIfVariableExistsInDictionary(string variable)
{
if (!VariableStorage.ContainsKey(variable))
{
VariableStorage.Add(variable, 0);
}
}
public Boolean EvalutateCondition()
{
return Operator(StringOperand, VariableStorage[VariableToEvaluate], ConditionalValue);
}
public Dictionary<string,int> ExecuteInstruction()
{
if(EvalutateCondition() == true)
{
VariableStorage[VariableToModify] = PlusOrMinus == "inc" ?
VariableStorage[VariableToModify] + ValueToModifyVariableBy :
VariableStorage[VariableToModify] - ValueToModifyVariableBy;
if(VariableStorage["Max"] < VariableStorage[VariableToModify])
{
VariableStorage["Max"] = VariableStorage[VariableToModify];
}
}
return VariableStorage;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment