Last active
December 13, 2020 09:41
-
-
Save felix-larsen/dfcc7da3e111db914cb70b9a21e762e5 to your computer and use it in GitHub Desktop.
13th December solution - Advent of Code 2020 - swift
This file contains hidden or 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
let departureTime = Int(lines[0])! | |
let busIds = lines[1].components(separatedBy: ",").compactMap{ Int($0) } | |
let minTimeToWait = busIds.map { busId in (busId, busId - (departureTime % busId)) }.min { first, second in first.1 < second.1 }! | |
print(minTimeToWait.0 * minTimeToWait.1) |
This file contains hidden or 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
// Chinese remainder theorem | |
let busIds = lines[1].components(separatedBy: ",").map{ Int($0) } | |
let busIdsWithOffset = busIds.enumerated().filter { (element) in | |
element.element != nil | |
} | |
let N = busIdsWithOffset.compactMap { $0.element }.reduce(1, *) | |
let result = busIdsWithOffset.map { ele in | |
let ni = ele.element! | |
let Ni = N / ni | |
let bi = (ni - ele.offset) % ni | |
if bi == 0 { | |
return 0 | |
} | |
var x = 0 | |
while( (Ni * x) % ni != 1) { | |
x += 1 | |
} | |
return bi * Ni * x | |
}.reduce(0, +) | |
print(result % N) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment