Last active
December 7, 2021 20:27
-
-
Save panicsteve/5e59709b6dfdb8bbfb9532ed435fc38c to your computer and use it in GitHub Desktop.
aoc2021-day6-part2
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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