DEV Community

Discussion on: Advent of Code 2019 Solution Megathread - Day 2: 1202 Program Alarm

Collapse
 
mellen profile image
Matt Ellen

In the browser!

function process(one, two)
{
    let pretext = document.getElementsByTagName('pre')[0].innerHTML;
    let instructions = pretext.split(',').map(i => parseInt(i, 10));
    instructions[1] = one;
    instructions[2] = two;
    for(let i = 0; i < instructions.length; i += 4)
    {
    let inst = instructions[i];
    if(inst == 99)
    {
        break;
    }

    let answerPos = instructions[i+3];
    let ai = instructions[i+1];
    let bi = instructions[i+2];

    if(inst == 1)
    {
        instructions[answerPos] = instructions[ai] + instructions[bi];
    }
    else if(inst == 2)
    {
        instructions[answerPos] = instructions[ai] * instructions[bi];
    }
    }

    return instructions[0];
}

/* part 2 */
let done = false;
for(let a = 0; a < 100 && !done; a++)
{
  for(let b = 0; b < 100; b++)
  {
    let n = process(a, b);
    if(n == 19690720)
    {
      console.log(a, b)
      done = true;
      break;
    }
  }
}