r/adventofcode • • Dec 07 '23

SOLUTION MEGATHREAD -❄️- 2023 Day 7 Solutions -❄️-

THE USUAL REMINDERS


AoC Community Fun 2023: ALLEZ CUISINE!

Today's secret ingredient is… *whips off cloth covering and gestures grandly*

Poetry

For many people, the craftschefship of food is akin to poetry for our senses. For today's challenge, engage our eyes with a heavenly masterpiece of art, our noses with alluring aromas, our ears with the most satisfying of crunches, and our taste buds with exquisite flavors!

  • Make your code rhyme
  • Write your comments in limerick form
  • Craft a poem about today's puzzle

    • Upping the Ante challenge: iambic pentameter
  • We're looking directly at you, Shakespeare bards and Rockstars

ALLEZ CUISINE!

Request from the mods: When you include a dish entry alongside your solution, please label it with [Allez Cuisine!] so we can find it easily!


--- Day 7: Camel Cards ---


Post your code solution in this megathread.

This thread will be unlocked when there are a significant number of people on the global leaderboard with gold stars for today's puzzle.

EDIT: Global leaderboard gold cap reached at 00:16:00, megathread unlocked!

50 Upvotes

1.0k comments sorted by

View all comments

1

u/malobebote Dec 07 '23 edited Dec 07 '23

[Language: Typescript]

My code isn't cute nor clever but it's simple.

My part 2 solution introduces a bestScore function that replaces all jokers with the most common card in hand. I originally brute-forced all combos but figured out later that this worked.

// Determines best score after replacing jokers.
// Replaces jokers with most common card in hand.
function bestScore(hand: Hand): number {
    const freq = frequencies(hand)
    if (freq.get('J') === 5) return score(['A', 'A', 'A', 'A', 'A'])
    const order = [ 'J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A', ]
    const sorted = hand
        .filter(([card]) => card !== 'J')
        .sort(
            (a, b) =>
                freq.get(b)! - freq.get(a)! ||
                order.indexOf(b) - order.indexOf(a),
        )
    return score(hand.map((card) => (card === 'J' ? sorted[0] : card)) as Hand)
}

Here's the full code:

const cards = ['2', '3', '4', '5', '6', '7', '8', '9', 'T', 'J', 'Q', 'K', 'A'] // part 1
const cards2 = ['J', '2', '3', '4', '5', '6', '7', '8', '9', 'T', 'Q', 'K', 'A'] // part 2

type Card = (typeof cards)[number]
type Hand = [Card, Card, Card, Card, Card]

// Counts the quantity of each item in an array.
// Example: 'aabddd' => { a: 2, b: 1, d: 3 }
function frequencies<T>(xs: T[]): Map<T, number> {
    const map = new Map()
    for (const x of xs) {
        map.set(x, (map.get(x) || 0) + 1)
    }
    return map
}

function score(hand: Hand): number {
    const freq = frequencies(hand)
    // Five of a kind
    if (freq.size === 1) return 7
    const counts = frequencies(Array.from(freq.values()))
    // Four of a kind
    if (counts.get(4) === 1) return 6
    // Full house
    if (counts.get(3) === 1 && counts.get(2) === 1) return 5
    // Three of a kind
    if (counts.get(3) === 1) return 4
    // Two pair '22334'
    if (counts.get(2) === 2) return 3
    // One pair '22345
    if (counts.get(2) === 1 && counts.get(1) === 3) return 2
    // High card '23456'
    if (counts.get(1) === 5) return 1
    return 0
}

// Determines best score after replacing jokers.
// Replaces jokers with most common card in hand.
function bestScore(hand: Hand): number {
    const freq = frequencies(hand)
    if (freq.get('J') === 5) return score(['A', 'A', 'A', 'A', 'A'])
    const sorted = hand
        .filter((card) => card !== 'J')
        .sort(
            (a, b) =>
                freq.get(b)! - freq.get(a)! ||
                cards2.indexOf(b) - cards2.indexOf(a),
        )
    return score(hand.map((card) => (card === 'J' ? sorted[0] : card)) as Hand)
}

function parse(input: string): { hand: Hand; bid: number }[] {
    const hands: { hand: Hand; bid: number }[] = []
    for (const line of input.trim().split('\n')) {
        const [a, b] = line.split(' ')
        const hand = a.split('') as Hand
        const bid = Number(b)
        hands.push({ hand, bid })
    }
    return hands
}

// Sorts hands by strength ascending
function compareHands(
    a: Hand,
    b: Hand,
    scorer: (hand: Hand) => number,
    cardOrder: Card[],
): number {
    function tieBreaker(a: Hand, b: Hand): number {
        for (let i = 0; i < a.length; i++) {
            if (a[i] === b[i]) continue
            return cardOrder.indexOf(a[i]) - cardOrder.indexOf(b[i])
        }
        return 0
    }

    return scorer(a) - scorer(b) || tieBreaker(a, b)
}

function part1(input: string) {
    const lines = parse(input)
    lines.sort((a, b) => compareHands(a.hand, b.hand, score, cards))
    let rank = 1
    let total = 0
    for (const line of lines) {
        total += line.bid * rank++
    }
    return total
}

function part2(input: string) {
    const lines = parse(input)
    lines.sort((a, b) => compareHands(a.hand, b.hand, bestScore, cards2))
    let rank = 1
    let total = 0
    for (const line of lines) {
        total += line.bid * rank++
    }
    return total
}

// const input = '32T3K 765\nT55J5 684\nKK677 28\nKTJJT 220\nQQQJA 483'
const input = readFileSync('day7.txt', { encoding: 'utf8' })

console.log('part 1:', part1(input))
console.log('part 2:', part2(input))

1

u/daggerdragon Dec 07 '23

Your code block is too long for the megathreads. Please edit your post to replace your oversized code with an external link to your code.