Created
December 8, 2017 19:09
-
-
Save timcreasy/e2ba5fb07d7592111f21d95e5c9698dc to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// Lessons learned - use Clojure | |
const fs = require('fs') | |
function parseInstruction(instruction) { | |
const regex = /([a-z]+) ([a-z]+) ([-]*[0-9]+) if ([a-z]+) ([><=!]+) ([-]*[0-9]+)/g | |
return regex.exec(instruction) | |
} | |
function parseInput(filePath) { | |
const input = fs.readFileSync(filePath, 'utf8').trim().split("\n"); | |
const parsedInput = input.map(function(instruction) { | |
const parsedInstruction = parseInstruction(instruction); | |
return {"register": parsedInstruction[1], | |
"action": parsedInstruction[2], | |
"amount": parseInt(parsedInstruction[3]), | |
"condition-op": parsedInstruction[5], | |
"condition-operand-1": parsedInstruction[4], | |
"condition-operand-2": parseInt(parsedInstruction[6])} | |
}) | |
return parsedInput; | |
} | |
function partOne(input) { | |
let registers = {} | |
const registerNames = new Set(input.map(function(data) { | |
return data["register"] | |
})) | |
for (let registerName of registerNames) { | |
registers[registerName] = 0 | |
} | |
const processedInput = input.reduce(function(regs, instruction) { | |
const conditionOperator = instruction["condition-op"] | |
let evaluatedCondition; | |
if (conditionOperator === ">") { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] > instruction["condition-operand-2"] | |
} else if (conditionOperator === "<") { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] < instruction["condition-operand-2"] | |
} else if (conditionOperator === "==") { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] == instruction["condition-operand-2"] | |
} else if (conditionOperator == "!=") { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] != instruction["condition-operand-2"] | |
} else if (conditionOperator == "<=") { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] <= instruction["condition-operand-2"] | |
} else { | |
evaluatedCondition = regs[instruction["condition-operand-1"]] >= instruction["condition-operand-2"] | |
} | |
if (evaluatedCondition) { | |
if (instruction["action"] == "inc") { | |
regs[instruction["register"]] = regs[instruction["register"]] + instruction["amount"] | |
} else { | |
regs[instruction["register"]] = regs[instruction["register"]] - instruction["amount"] | |
} | |
} | |
return regs | |
}, registers) | |
return Object.values(processedInput).reduce(function(a, b) { | |
return Math.max(a, b); | |
}); | |
} | |
console.log(partOne(parseInput("./input.txt"))) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment