DEV Community is a community of 861,926 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Quentin Ménoret

Posted on

Advent of code - Day 11

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.

Part 1 of day 11 was a simple game of life exercise. I liked the part 2 more, it was a bit different for once.

Here is my solution for day #11:

``````function isOccupied(rows, x, y, direction, log = false) {
if (log) console.log(x, y, direction)
if (!(rows[x] || [])[y]) return false
if (rows[x][y] === 'L') return false
if (rows[x][y] === '#') return true
return isOccupied(rows, x + direction[0], y + direction[1], direction, log)
}

function getNextTurn(rows) {
return rows.map((row, rowIndex) =>
row.map((seat, seatIndex) => {
if (seat === '.') return '.'
const numberOfSeatTaken = [
[-1, -1],
[-1, 0],
[-1, 1],
[1, -1],
[1, 0],
[1, 1],
[0, -1],
[0, 1],
].filter(([x, y]) => {
return isOccupied(rows, rowIndex + x, seatIndex + y, [x, y])
}).length
if (seat === '#') return numberOfSeatTaken >= 5 ? 'L' : '#'
return numberOfSeatTaken > 0 ? 'L' : '#'
}),
)
}

function areEquals(rows1, rows2) {
return rows1.map((x) => x.join('')).join('\n') === rows2.map((x) => x.join('')).join('\n')
}

let previous = input
let current = getNextTurn(previous)

while (!areEquals(previous, current)) {
previous = current
current = getNextTurn(previous)
}

console.log(current.reduce((acc, row) => row.reduce((acc, seat) => (seat === '#' ? acc + 1 : acc), acc), 0))
``````