Skip to content

Instantly share code, notes, and snippets.

@Friss
Last active December 8, 2020 05:49
Show Gist options
  • Save Friss/9b24771d784b5676ff9cf835537c22ff to your computer and use it in GitHub Desktop.
Save Friss/9b24771d784b5676ff9cf835537c22ff to your computer and use it in GitHub Desktop.
const fs = require('fs').promises;
(async () => {
console.log(`Reading input from ${__dirname}/${process.argv[2]}.txt`);
const inputData = await fs.readFile(`${__dirname}/${process.argv[2]}.txt`);
const inputs = inputData
.toString()
.split('\n')
.filter((n) => n);
let acc = 0;
let index = 0;
const visitedIndexs = new Set();
while (true) {
if (visitedIndexs.has(index)) {
console.log('acc', acc);
break;
}
visitedIndexs.add(index);
const line = inputs[index];
const [inc, value] = line.split(' ');
switch (inc) {
case 'nop': {
index++;
break;
}
case 'jmp': {
index += parseInt(value, 10);
break;
}
case 'acc': {
index++;
acc += parseInt(value, 10);
break;
}
}
}
console.log('---');
for (let changeIndex = 0; changeIndex < inputs.length; changeIndex++) {
const puzzleInput = [...inputs];
if (puzzleInput[changeIndex].includes('nop')) {
puzzleInput[changeIndex] = puzzleInput[changeIndex].replace('nop', 'jmp');
} else if (puzzleInput[changeIndex].includes('jmp')) {
puzzleInput[changeIndex] = puzzleInput[changeIndex].replace('jmp', 'nop');
} else {
continue;
}
let acc2 = 0;
let index2 = 0;
const visitedIndexs2 = new Set();
while (true) {
if (visitedIndexs2.has(index2)) {
break;
}
if (index2 >= puzzleInput.length) {
console.log(
'Winning change index',
changeIndex,
'out of',
inputs.length
);
console.log('acc2', acc2);
return;
}
visitedIndexs2.add(index2);
const line = puzzleInput[index2];
const [inc, value] = line.split(' ');
switch (inc) {
case 'nop': {
index2++;
break;
}
case 'jmp': {
index2 += parseInt(value, 10);
break;
}
case 'acc': {
index2++;
acc2 += parseInt(value, 10);
break;
}
}
}
}
})();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment