aoc2021/Sources/06/06.swift
2021-12-06 20:50:41 +01:00

41 lines
1.1 KiB
Swift

//
// File.swift
//
//
// Created by Max Nuding on 05.12.21.
//
import Foundation
import Runner
struct Day06: Runnable {
let inputPath: String
func run() {
let input = try! String(contentsOfFile: inputPath)
let internalCounters = input
.trimmingCharacters(in: .newlines)
.components(separatedBy: ",")
.map { Int($0)! }
run(fish: internalCounters, numDays: 80)
run(fish: internalCounters, numDays: 256)
}
func run(fish: [Int], numDays: Int) {
var fishCount = Dictionary(grouping: fish, by: { $0 }).mapValues { $0.count }
for _ in 1...numDays {
var tmpFishCount = fishCount
.filter { $0.key >= 0 }
.reduce(into: [:]) { $0[$1.key-1, default: 0] = $1.value }
let countPregnant = tmpFishCount[-1] ?? 0
tmpFishCount[8] = countPregnant
tmpFishCount[6] = (tmpFishCount[6] ?? 0) + countPregnant
tmpFishCount[-1] = 0
fishCount = tmpFishCount
}
print(fishCount.values.reduce(0, +))
}
}