Skip to content

Instantly share code, notes, and snippets.

@chunkydotdev
Last active December 2, 2019 21:49
Show Gist options
  • Save chunkydotdev/2d01bd74fecec4d3ddc9c11b9101111d to your computer and use it in GitHub Desktop.
Save chunkydotdev/2d01bd74fecec4d3ddc9c11b9101111d to your computer and use it in GitHub Desktop.
Adventure of code Day 2 Problem 2 in Typescript
export default class RocketComputer {
constructor() {
let opCode = [1, 12, 2, 3, 1, 1, 2, 3, 1, 3, 4, 3, 1, 5, 0, 3, 2, 1, 10, 19, 1, 6, 19, 23, 1, 13, 23, 27, 1, 6, 27, 31, 1, 31, 10, 35, 1, 35, 6, 39, 1, 39, 13, 43, 2, 10, 43, 47, 1, 47, 6, 51, 2, 6, 51, 55, 1, 5, 55, 59, 2, 13, 59, 63, 2, 63, 9, 67, 1, 5, 67, 71, 2, 13, 71, 75, 1, 75, 5, 79, 1, 10, 79, 83, 2, 6, 83, 87, 2, 13, 87, 91, 1, 9, 91, 95, 1, 9, 95, 99, 2, 99, 9, 103, 1, 5, 103, 107, 2, 9, 107, 111, 1, 5, 111, 115, 1, 115, 2, 119, 1, 9, 119, 0, 99, 2, 0, 14, 0];
let problem1Result = this.calculateIntCodeList(opCode);
console.log('position 0 number: ', problem1Result[0]);
let problem2Result = this.calculateIntCodeNounAndVerb(opCode, 19690720);
console.log('100 * noun + verb is: ', problem2Result);
}
public calculateIntCodeList(memory: number[]): number[] {
let result = [...memory];
for (let instructionPointer = 0; instructionPointer < memory.length; instructionPointer += 4) {
if (result[instructionPointer] === 99) {
return result;
} else if (result[instructionPointer] === 1) {
const address1 = result[instructionPointer + 1];
const address2 = result[instructionPointer + 2];
const address3 = result[instructionPointer + 3];
result[address3] = result[address1] + result[address2];
} else if (result[instructionPointer] === 2) {
const address1 = result[instructionPointer + 1];
const address2 = result[instructionPointer + 2];
const address3 = result[instructionPointer + 3];
result[address3] = result[address1] * result[address2];
}
}
return result;
}
public calculateIntCodeNounAndVerb(memory: number[], result: number): number {
let noun = 1;
let verb = 1;
let currentResultAttempt = 0;
while (true) {
while (currentResultAttempt < result) {
noun += 1;
let newInstruction = [...memory];
newInstruction[1] = noun;
newInstruction[2] = verb;
currentResultAttempt = this.calculateIntCodeList(newInstruction)[0];
if (currentResultAttempt === result) {
return 100 * noun + verb;
}
}
verb += 1;
noun = 1;
currentResultAttempt = 0;
}
return 0;
}
}
new RocketComputer();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment