adventofcode-2016/day12/part2.js

56 lines
1.4 KiB
JavaScript
Raw Normal View History

2016-12-13 08:20:24 +00:00
var instructions = [];
var registers = {a: 0, b: 0, c: 1, d: 0};
var instructionSet = {};
instructionSet.cpy = (a, b)=>{
if(Number.isInteger(parseInt(a))){
registers[b] = parseInt(a);
}
else{
registers[b] = registers[a];
}
}
instructionSet.inc = (a)=>{
registers[a]++;
}
instructionSet.dec = (a)=>{
registers[a]--;
}
instructionSet.jnz = (a, b)=>{
if((registers[a] != 0) || ((parseInt(a) != 0) && (!isNaN(parseInt(a))))){
pc = pc + (parseInt(b) - 1);
}
}
var input = require("fs").readFileSync("input.txt").toString().replace(/\r/g, "");
var instructions = input.split("\n").filter((a)=>(a)).map((instruction)=>{
if(instruction.indexOf("cpy") > -1){
var instructionParts = instruction.match("cpy ([^ ]+) ([^ ]+)");
return ["cpy", [instructionParts[1], instructionParts[2]]];
}
if(instruction.indexOf("inc") > -1){
var instructionParts = instruction.match("inc ([^ ]+)");
return ["inc", [instructionParts[1]]];
}
if(instruction.indexOf("dec") > -1){
var instructionParts = instruction.match("dec ([^ ]+)");
return ["dec", [instructionParts[1]]];
}
if(instruction.indexOf("jnz") > -1){
var instructionParts = instruction.match("jnz ([^ ]+) ([^ ]+)");
return ["jnz", [instructionParts[1], instructionParts[2]]];
}
});
var pc = 0;
while(pc < instructions.length){
instructionSet[instructions[pc][0]].apply(null, instructions[pc][1]);
pc++;
}
console.log(registers);
console.log(registers[a]);