This repository has been archived by the owner on Oct 30, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
seating-system.js
128 lines (119 loc) · 3.37 KB
/
seating-system.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
const fs = require("fs");
let values = fs.readFileSync("input.txt", "utf8").split("\r\n"); //Reads the values
const directions = [
[-1,-1],
[-1, 0],
[-1, 1],
[ 0,-1],
[ 0, 1],
[ 1,-1],
[ 1, 0],
[ 1, 1]
]
function count_occupied(seats) {
const occupied = seats.reduce((occupied, row) => {
return (
occupied + row.split('').reduce((sum, seat) => sum + +(seat === '#'), 0)
);
}, 0);
return occupied
}
function equal_seating(a, b) {
return (a.join() === b.join())
}
function apply_rules(prev) {
seats = []
for (let i = 0; i < prev.length; i++) {
seats.push([]);
for (let j = 0; j < prev[0].length; j++) {
const seat = prev[i][j];
if (seat === '.') {
seats[i].push('.');
} else {
const adjacents = directions.reduce((adjacents, [dy, dx]) => {
return (
adjacents + +(!!prev[i + dy] && prev[i + dy][j + dx] === '#')
);
}, 0);
if (seat === 'L') {
seats[i].push(
adjacents == 0
? '#'
: 'L'
)
} else if (seat === '#') {
seats[i].push(
adjacents >= 4
? 'L'
: '#'
)
}
}
}
seats[i] = seats[i].join('');
}
return seats
}
function solve_part_one() {
let prev
let seats = values
do {
prev = seats
seats = apply_rules(seats)
} while (!equal_seating(prev, seats))
return count_occupied(seats)
}
function getAdjacents(prev, i, j) {
return directions.reduce((adjacents, [dy, dx]) => {
let ci = i + dy
let cj = j + dx
let currAdjacents = 0
while (prev[ci] && prev[ci][cj]) {
if (prev[ci][cj] == '#') {
currAdjacents = 1
break
} else if (prev[ci][cj] == 'L') {
break
}
ci += dy
cj += dx
}
return adjacents + currAdjacents
}, 0)
}
function solve_part_two() {
let prev
let seats = values
do {
prev = seats
seats = []
for (let i = 0; i < prev.length; i++) {
seats.push([]);
for (let j = 0; j < prev[0].length; j++) {
const seat = prev[i][j];
if (seat === '.') {
seats[i].push('.');
} else {
const adjacents = getAdjacents(prev, i, j)
if (seat === 'L') {
seats[i].push(
adjacents == 0
? '#'
: 'L'
)
} else if (seat === '#') {
seats[i].push(
adjacents >= 5
? 'L'
: '#'
)
}
}
}
seats[i] = seats[i].join('');
}
} while (!equal_seating(prev, seats))
return count_occupied(seats)
}
console.log(solve_part_one())
console.log(solve_part_two())