DEV Community

loading...
Cover image for Advent of code - Day 15

Advent of code - Day 15

qmenoret profile image Quentin Ménoret ・1 min read

Are you participating in the Advent of code this year?

If you don't know what the advent of code is, it's a website where you'll find a daily challenge (every day it gets harder). It's a really fun event, you should participate!

I try to solve the exercises using either JavaScript or TypeScript and will share my solutions daily (with one day delay so no one can cheat!). I only share the solution for the second part.

Ok, I'm pretty sure they decided to give us a break following the weekend that was way harder than the rest! Good for us, this one was pretty simple.

Here is my solution for day #15:

const input = `14,1,17,0,3,20`.split(',')

// Pre alloc the array for performance
const record = new Array(30000000)

function process(number, index) {
  const firstSeen = record[number] === undefined
  const seen = record[number]
  record[number] = index
  return firstSeen ? 0 : index - seen
}

let lastSeenWas = 0
for (let i = 0; i < input.length; i++) lastSeenWas = process(input[i], i)

for (let i = input.length; i < 30000000 - 1; i++) {
  lastSeenWas = process(lastSeenWas, i)
}

console.log(lastSeenWas)
Enter fullscreen mode Exit fullscreen mode

Feel free to share your solution in the comments!


Photo by Markus Spiske on Unsplash

Discussion (0)

pic
Editor guide