Skip to content

Instantly share code, notes, and snippets.

@panicsteve
Last active December 7, 2021 20:27
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 panicsteve/5e59709b6dfdb8bbfb9532ed435fc38c to your computer and use it in GitHub Desktop.
Save panicsteve/5e59709b6dfdb8bbfb9532ed435fc38c to your computer and use it in GitHub Desktop.
aoc2021-day6-part2
import Foundation
func loadInput() -> [Int] {
let url = URL(fileURLWithPath: "/Volumes/Synology/Projects/Advent of Code 2021/Day 6/input-1.txt")
var s = ""
do {
s = try String(contentsOf: url)
}
catch {
print("Can't open \(url)")
return []
}
let input = s.split(separator: ",")
var allFish: [Int] = []
for inputLine in input {
allFish.append(Int(inputLine)!)
}
return allFish
}
func calcPopulationFromOneFish(startValue: Int, days: Int) -> Int
{
var val = startValue
var pop = 1
var spawned = false
for day in 1 ... days {
spawned = false
val -= 1
if val == 0 {
spawned = true
val = 7
}
if spawned {
let daysLeft = days - day
if daysLeft > 0 {
let cachedValue = cache[daysLeft]
if cachedValue == -1 {
let spawnedFishPopulation = calcPopulationFromOneFish(startValue: 9, days: daysLeft)
pop += spawnedFishPopulation
cache[daysLeft] = spawnedFishPopulation
}
else {
pop += cachedValue
}
}
}
}
return pop
}
func part2() {
var total = 0
let days = 256
for startVal in allFish {
let result = calcPopulationFromOneFish(startValue: startVal, days: days)
total += result
}
print(total)
}
let allFish = loadInput()
print("Initial state: \(allFish)")
var cache: [Int] = Array(repeating: -1, count: 1000)
part2()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment