Created
December 5, 2021 10:25
-
-
Save tluyben/eb9a3070865efb8a26af9d5fc61e3a3c to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import { accessSync, promises as fs } from 'fs'; | |
(async()=>{ | |
const input = await fs.readFile("./interpretertests/aoc_21_4_input.txt", 'utf8')+'\n' | |
const lines = input.split('\n') | |
const draw = lines[0].split(',').map(Number) | |
const boards = lines.slice(1).reduce((acc, line)=>{ | |
if (line.trim().length==0) { | |
if (acc.current.length>0) { | |
acc.boards.push(acc.current) | |
acc.current = [] | |
} | |
return acc | |
} | |
const numbers = line.split(' ').filter(v=>v.trim().length>0).map(Number).map(v=>[v, false]) | |
acc.current.push(numbers) | |
return acc | |
}, {boards: [], current: []}) | |
// # 1 | |
for(const d of draw) { | |
boards.boards.forEach(b=>b.forEach(n=>n.filter(v=>v[0] == d).forEach(v=>v[1]=true))); | |
const winner = boards.boards.filter( | |
b=> | |
b.filter(n=>n.every(v=>v[1])).length>0 | |
|| | |
b[0].map((val, index)=>b.map(row => row[index]).reverse()).filter(n=>n.every(v=>v[1])).length>0 | |
)[0] | |
if (winner) { | |
console.table(winner) | |
console.log(winner.flatMap(r=>r.filter(v=>!v[1]).map(v=>v[0])).reduce((acc, cur) => acc + cur, 0) * d) | |
break; | |
} | |
} | |
// # 2 | |
boards.boards.forEach(b=>b.forEach(n=>n.forEach(v=>v[1]=false))); // reset boards | |
let lastWinners = [] | |
let winners = [] | |
for(const d of draw) { | |
lastWinners = winners | |
boards.boards.forEach(b=>b.forEach(n=>n.filter(v=>v[0] == d).forEach(v=>v[1]=true))); | |
winners = boards.boards.filter( | |
b=> | |
b.filter(n=>n.every(v=>v[1])).length>0 | |
|| | |
b[0].map((val, index)=>b.map(row => row[index]).reverse()).filter(n=>n.every(v=>v[1])).length>0 | |
).map(b=>boards.boards.indexOf(b)) | |
if (winners.length == boards.boards.length) { | |
const winner = boards.boards[winners.filter(v=>!lastWinners.includes(v))[0]] | |
console.table(winner) | |
console.log(winner.flatMap(r=>r.filter(v=>!v[1]).map(v=>v[0])).reduce((acc, cur) => acc + cur, 0) * d) | |
break; | |
} | |
} | |
})() |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment