From 85cfa9003d172772065be8c92dfd8d4b4a0edef4 Mon Sep 17 00:00:00 2001 From: Max Nuding Date: Mon, 6 Dec 2021 20:23:00 +0100 Subject: [PATCH] 06b --- Sources/06/06.swift | 42 +++++++++------------- Sources/Runner/Resources/input/06_test.txt | 1 + 2 files changed, 18 insertions(+), 25 deletions(-) create mode 100644 Sources/Runner/Resources/input/06_test.txt diff --git a/Sources/06/06.swift b/Sources/06/06.swift index 8a65fa2..3ad671c 100644 --- a/Sources/06/06.swift +++ b/Sources/06/06.swift @@ -8,25 +8,6 @@ import Foundation import Runner -class Fish: CustomStringConvertible { - var timer: Int - - var description: String { "\(timer)"} - - init(timer: Int = 8) { - self.timer = timer - } - - func tick() -> Fish? { - timer -= 1 - if timer < 0 { - timer = 6 - return Fish() - } - return nil - } -} - struct Day06: Runnable { let inputPath: String @@ -35,15 +16,26 @@ struct Day06: Runnable { let internalCounters = input .trimmingCharacters(in: .newlines) .components(separatedBy: ",") - .map { Fish(timer: Int($0)!) } + .map { Int($0)! } run(fish: internalCounters, numDays: 80) + run(fish: internalCounters, numDays: 256) } - func run(fish: [Fish], numDays: Int) { - var tmpFish = fish - for _ in 1...numDays { - tmpFish.append(contentsOf: tmpFish.compactMap { $0.tick() }) + func run(fish: [Int], numDays: Int) { + var tmpFish = Dictionary(grouping: fish, by: { $0 }).mapValues { $0.count } + + for _ in 1...numDays { + var d = [Int:Int]() + for f in tmpFish.keys.filter({$0 >= 0}) { + d[f-1] = tmpFish[f] + } + let countPregnant = d[-1] ?? 0 + d[8] = countPregnant + d[6] = (d[6] ?? 0) + countPregnant + d[-1] = 0 + + tmpFish = d } - print(tmpFish.count) + print(tmpFish.values.reduce(0, +)) } } diff --git a/Sources/Runner/Resources/input/06_test.txt b/Sources/Runner/Resources/input/06_test.txt new file mode 100644 index 0000000..55129f1 --- /dev/null +++ b/Sources/Runner/Resources/input/06_test.txt @@ -0,0 +1 @@ +3,4,3,1,2