this post was submitted on 01 Dec 2023
18 points (100.0% liked)

NotAwfulTech

358 readers
11 users here now

a community for posting cool tech news you don’t want to sneer at

non-awfulness of tech is not required or else we wouldn’t have any posts

founded 1 year ago
MODERATORS
 

Rules: no spoilers.

The other rules are made up as we go along.

Share code by link to a forge, home page, pastebin (Eric Wastl has one here) or code section in a comment.

you are viewing a single comment's thread
view the rest of the comments
[–] [email protected] 4 points 11 months ago

Day 4: Scratchcards

Late to the party and never done advents before, I liked how this problem reminded me that tree traversal is thing, almost as much as I don't that so much of my career involves powershell now.

I'm putting everything up at https://github.com/SpaceAntelope/advent-of-code-2023 except the input files.

Using command abbreviations like % and ? to keep the horizontal length friendly to lemmy post areas, they are expanded in git.

Part 2 in Powershell

function calculate([string]$data) {
  # code for parsing data and calculating matches from pt1 here, check the github link if you like banal regexps
  # returns objects with the relevant fields being the card index and the match count
}

function calculateAccumulatedCards($data) {
    $cards = calculate $data # do pt1 calculations

    $cards 
    | ? MatchCount -gt 0 # otherwise the losing card becomes its own child and the search cycles to overflow
    | % { 
        $children = ($_.Index + 1) .. ($_.Index + $_.MatchCount)  # range of numbers corresponding to indices of cards won
        | % { $cards[$_ - 1] } # map to the actual cards
        | ? { $null -ne $_ }  # filter out overflow when index exceeds input length

        $_ | Add-Member -NotePropertyName Children -NotePropertyValue $children # add cards gained as children property
    }

    # do depth first search on every card and its branching children while counting every node
    # the recursive function is inlined in the foreach block because it's simpler than referencing it 
    # from outside the parallel scope
    $cards | % -Parallel {
        function traverse($card) {
            $script:count++        
            foreach ($c in $card.Children) { traverse($c) }
        }
        
        $script:count = 0 # script: means it's basically globally scoped
        traverse $_ 
        $script:count # pass node count to pipeline     
    } 
    | measure -sum    
    | % sum
}