-
-
Save Yazir/013634809c5cbcc94d69b10fc1ab8f10 to your computer and use it in GitHub Desktop.
aoc 2023 - #4 part 1+2
This file contains 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
{ | |
const input = document.body.innerText.trim() | |
const cardsRaw = input.split("\n") | |
// Parse | |
/** @typedef {{idx: number, winning : number[], scratched : number[]}} Card */ | |
/** @type {Card[]} */ | |
const cards = [] | |
for (let i = 0; i < cardsRaw.length; i++) { | |
const cardStr = cardsRaw[i]; | |
const [first, second] = cardStr.split("|") | |
function parseNumbers (str) { | |
return str.split(" ") | |
.map(s => s.trim()) | |
.filter(s => s !== "") | |
.map(s => Number(s)) | |
} | |
const winning = parseNumbers(first.split(":")[1]) | |
const scratched = parseNumbers(second) | |
cards.push({idx: i, winning, scratched}) | |
} | |
function answerP1() { | |
let pointsSum = 0 | |
for (const card of cards) { | |
let value = 0 | |
for (const number of card.winning) { | |
if (card.scratched.includes(number)) { | |
value = value === 0 ? 1 : value * 2 | |
} | |
} | |
pointsSum += value | |
} | |
return pointsSum | |
} | |
function answerP2() { | |
/** @type {Card[]} */ | |
const cardsNew = [...cards] | |
for (let i = 0; i < cardsNew.length; i++) { | |
const card = cardsNew[i] | |
let matches = 0 | |
for (const number of card.winning) { | |
if (card.scratched.includes(number)) { | |
matches ++ | |
} | |
} | |
for (let j = 1; j < matches + 1; j++) { | |
cardsNew.push(cards[card.idx+j]) | |
} | |
} | |
return cardsNew.length | |
} | |
console.log("answer p1", answerP1()) | |
console.log("answer p2", answerP2()) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
could be made efficiently without copying cards in the P2. Instead cache amount of copies in the original card data and sum up copies that way, pretty much no LOC difference.