aoc2021/Sources/06/06.swift

41 lines
1.1 KiB
Swift
Raw Permalink Normal View History

2021-12-06 18:37:25 +00:00
//
// 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: ",")
2021-12-06 19:23:00 +00:00
.map { Int($0)! }
2021-12-06 18:37:25 +00:00
run(fish: internalCounters, numDays: 80)
2021-12-06 19:23:00 +00:00
run(fish: internalCounters, numDays: 256)
2021-12-06 18:37:25 +00:00
}
2021-12-06 19:23:00 +00:00
func run(fish: [Int], numDays: Int) {
2021-12-06 19:50:41 +00:00
var fishCount = Dictionary(grouping: fish, by: { $0 }).mapValues { $0.count }
2021-12-06 19:23:00 +00:00
for _ in 1...numDays {
2021-12-06 19:50:41 +00:00
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
2021-12-06 19:23:00 +00:00
2021-12-06 19:50:41 +00:00
fishCount = tmpFishCount
2021-12-06 18:37:25 +00:00
}
2021-12-06 19:50:41 +00:00
print(fishCount.values.reduce(0, +))
2021-12-06 18:37:25 +00:00
}
}