Skip to content

Instantly share code, notes, and snippets.

@Yazir
Created December 4, 2023 14:30
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save Yazir/013634809c5cbcc94d69b10fc1ab8f10 to your computer and use it in GitHub Desktop.
Save Yazir/013634809c5cbcc94d69b10fc1ab8f10 to your computer and use it in GitHub Desktop.
aoc 2023 - #4 part 1+2
{
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())
}
@Yazir
Copy link
Author

Yazir commented Dec 4, 2023

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.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment