summaryrefslogtreecommitdiffstats
path: root/day11/day11-2.js
diff options
context:
space:
mode:
authorGravatar Piotr Russ <piotr.russ@betvictor.com> 2020-12-12 10:38:29 +0100
committerGravatar Piotr Russ <piotr.russ@betvictor.com> 2020-12-12 10:38:29 +0100
commit2fdbbd79bed58399ab63f92ece74fe6abb450b9c (patch)
tree0db1e2966276d22d3972c2d3ef0a89fc22affdb0 /day11/day11-2.js
parent468e261bccd8fc44ee6ffd3e7fda1c3659a7ab1d (diff)
downloadadvent_of_code_2020-2fdbbd79bed58399ab63f92ece74fe6abb450b9c.tar.gz
advent_of_code_2020-2fdbbd79bed58399ab63f92ece74fe6abb450b9c.tar.bz2
advent_of_code_2020-2fdbbd79bed58399ab63f92ece74fe6abb450b9c.zip
day11
Diffstat (limited to 'day11/day11-2.js')
-rw-r--r--day11/day11-2.js50
1 files changed, 50 insertions, 0 deletions
diff --git a/day11/day11-2.js b/day11/day11-2.js
new file mode 100644
index 0000000..5d72f0f
--- /dev/null
+++ b/day11/day11-2.js
@@ -0,0 +1,50 @@
+const data = require('./data')
+const rows = data.split(/\n/g).filter(r => r)
+const rowsLn = rows[0].length
+const string = rows.join('')
+
+const checkSeat = (i, s) => {
+ const lookup = (index, posCheck, next) => {
+ const nextIndex = next(index)
+ return posCheck(index)
+ ? (s[nextIndex] !== '.' ? s[nextIndex] : lookup(nextIndex, posCheck, next))
+ : '.'
+ }
+
+ const around = [
+ lookup(i, i => (i >= rowsLn), i => (i-rowsLn)), // Top
+ lookup(i, i => (i >= rowsLn && (i+1)%rowsLn !== 0), i => (i+1-rowsLn)), // T-R
+ lookup(i, i => ((i+1)%rowsLn !== 0), i => (i+1)), // Rigth
+ lookup(i, i => (i < s.length - rowsLn && (i+1)%rowsLn !== 0), i => (i+1+rowsLn)), // B-R
+ lookup(i, i => (i < s.length - rowsLn), i => (i+rowsLn)), // Bottom
+ lookup(i, i => (i%rowsLn !== 0 && i < s.length -rowsLn), i => (i-1+rowsLn)), // B-L
+ lookup(i, i => (i%rowsLn !== 0), i => (i-1)), // Left
+ lookup(i, i => (i > rowsLn && i%rowsLn > 0), i => (i-1-rowsLn)), // T-L
+ ]
+
+ const taken = around.filter(s => s === '#').length
+ const free = around.filter(s => s === 'L').length
+
+ return [taken, free]
+}
+
+const round = (str) => {
+ const newArray = []
+ str.split('').forEach((s, i) => {
+ const [taken, free] = checkSeat(i, str)
+ if (s === 'L' && taken === 0) {
+ newArray[i] = '#'
+ } else if (s === '#' && taken >= 5) {
+ newArray[i] = 'L'
+ } else {
+ newArray[i] = str[i]
+ }
+ })
+
+ const newString = newArray.join('')
+ return newString === str
+ ? newString.split('').filter(s => s === '#').length
+ : round(newString)
+}
+
+console.log(round(string))