|
| 1 | +const cloneSeats = (seats: string[][]) => JSON.parse(JSON.stringify(seats)); |
| 2 | + |
| 3 | +const countOccupiedSeats = (seats: string[]) => { |
| 4 | + return seats.reduce((acc, seat) => { |
| 5 | + if (seat === '#') return acc + 1; |
| 6 | + return acc; |
| 7 | + }, 0); |
| 8 | +}; |
| 9 | + |
| 10 | +type Directions = Record<string, number[]>; |
| 11 | + |
| 12 | +export const countAdjacentSeats = (seats: string[][], i: number, j: number) => { |
| 13 | + const directions: Directions = { |
| 14 | + UP: [0, -1], |
| 15 | + DOWN: [0, 1], |
| 16 | + LEFT: [-1, 0], |
| 17 | + RIGHT: [1, 0], |
| 18 | + UP_LEFT: [-1, -1], |
| 19 | + UP_RIGHT: [1, -1], |
| 20 | + DOWN_LEFT: [-1, 1], |
| 21 | + DOWN_RIGHT: [1, 1], |
| 22 | + }; |
| 23 | + |
| 24 | + return Object.keys(directions).reduce((count, direction) => { |
| 25 | + const [stepX, stepY] = directions[direction]; |
| 26 | + let x = j + stepX; |
| 27 | + let y = i + stepY; |
| 28 | + |
| 29 | + while (x >= 0 && x < seats[0].length && y >= 0 && y < seats.length) { |
| 30 | + if (seats[y][x] === 'L') return count; |
| 31 | + else if (seats[y][x] === '#') return count + 1; |
| 32 | + x += stepX; |
| 33 | + y += stepY; |
| 34 | + } |
| 35 | + return count; |
| 36 | + }, 0); |
| 37 | +}; |
| 38 | + |
| 39 | +const updateSeats = (seats: string[][]): string[][] => { |
| 40 | + const newSeats = cloneSeats(seats); |
| 41 | + let seatChanged = false; |
| 42 | + for (let i = 0; i < seats.length; i++) { |
| 43 | + for (let j = 0; j < seats[0].length; j++) { |
| 44 | + const currentSeat = seats[i][j]; |
| 45 | + if (currentSeat === '.') continue; |
| 46 | + if (currentSeat === 'L') { |
| 47 | + if (countAdjacentSeats(seats, i, j) === 0) { |
| 48 | + newSeats[i][j] = '#'; |
| 49 | + seatChanged = true; |
| 50 | + } |
| 51 | + } else if (currentSeat === '#') { |
| 52 | + if (countAdjacentSeats(seats, i, j) >= 5) { |
| 53 | + newSeats[i][j] = 'L'; |
| 54 | + seatChanged = true; |
| 55 | + } |
| 56 | + } |
| 57 | + } |
| 58 | + } |
| 59 | + // Update seats if state has changed |
| 60 | + if (seatChanged) { |
| 61 | + return updateSeats(cloneSeats(newSeats)); |
| 62 | + } |
| 63 | + return seats; |
| 64 | +}; |
| 65 | + |
| 66 | +export const part2 = (input: string) => { |
| 67 | + const seats = input.split('\n').map(a => a.split('')); |
| 68 | + return countOccupiedSeats(updateSeats(seats).join(',').split(',')); |
| 69 | +}; |
| 70 | + |
| 71 | +// const printSeats = (seats: string[][]) => { |
| 72 | +// console.log(seats.map(seat => seat.join('').slice(0) + '\n').join('')); |
| 73 | +// }; |
0 commit comments