Skip to content

Instantly share code, notes, and snippets.

@akaralar
Created December 11, 2020 03:18
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 akaralar/ded8ab3fd3325fb3762dce925692f699 to your computer and use it in GitHub Desktop.
Save akaralar/ded8ab3fd3325fb3762dce925692f699 to your computer and use it in GitHub Desktop.
AoC 2020 Day 10
import Foundation
final class Day1020: Day {
override func perform() {
let input = String.input(forDay: 10, year: 2020)
var joltages = input
.split(separator: "\n")
.map(String.init)
.map(Int.init)
.compactMap { $0 }
.sorted()
joltages = [0] + joltages + [joltages.max()! + 3]
print(part1(joltages))
print(part2(joltages))
}
func part1(_ joltages: [Int]) -> Int {
let (ones, threes) = zip(joltages, joltages.dropFirst())
.reduce((ones: 0, threes: 0)) { (result, next) in
switch next.1 - next.0 {
case 1: return (result.0+1, result.1)
case 3: return (result.0, result.1+1)
default: return result
}
}
return ones * threes
}
func part2(_ joltagesIncludingBounds: [Int]) -> Int {
var initialCache = [joltagesIncludingBounds.max()!: 1]
return countJoltageArrangements(joltagesIncludingBounds.dropLast(), cache: &initialCache)
}
func countJoltageArrangements(_ joltages: [Int], cache: inout [Int: Int]) -> Int {
guard let last = joltages.last else { return cache[0, default: 0] }
cache[last] = (1...3)
.map { cache[last+$0, default: 0] }
.reduce(0, +)
return countJoltageArrangements(joltages.dropLast(), cache: &cache)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment