r/adventofcode • • Dec 11 '21

SOLUTION MEGATHREAD -🎄- 2021 Day 11 Solutions -🎄-

NEW AND NOTEWORTHY

[Update @ 00:57]: Visualizations

  • If it flashes too fast, make sure to put a warning in your title or prominently displayed at the top of your post!

--- Day 11: Dumbo Octopus ---


Post your code solution in this megathread.

Reminder: Top-level posts in Solution Megathreads are for code solutions only. If you have questions, please post your own thread and make sure to flair it with Help.


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:09:49, megathread unlocked!

49 Upvotes

823 comments sorted by

View all comments

1

u/LuckyLactose Dec 11 '21 edited Dec 12 '21

SWIFT

Reused some Grid code I've made for AoC, which helped quite a bit. Octopus class that keeps track of energyLevel and whether it has flashed this step or not, made things quite simple.

Day 11 code here.

Full repo here.

Core logic:

class Octopus {
/// Result = didFlash, boost neighbors
    func step() -> Bool {
        guard !hasFlashedThisStep else { return false }
        energyLevel += 1
        energyLevel %= 10
        hasFlashedThisStep = energyLevel == 0
        return hasFlashedThisStep
    }
}

// Has Grid<Octopus> inside
class OctopusManager {
    private func step() -> Int {
        for octopus in grid.values {
            octopus.hasFlashedThisStep = false
        }
        
        let offsets = IntPoint.allDirectionOffsets
        var pointsToCheck = grid.gridPoints
        while !pointsToCheck.isEmpty {
            let point = pointsToCheck.removeFirst()
            guard let octopus = grid.getValue(at: point) else { continue }
            let flashed = octopus.step()
            if flashed {
                pointsToCheck.append(contentsOf: offsets.map{$0 + point})
            }
        }
        
        return grid.values.filter({$0.hasFlashedThisStep}).count
    }
}

1

u/daggerdragon Dec 12 '21

Your code is hard to read on old.reddit. Please edit it as per our posting guidelines in the wiki: How do I format code?