Skip to content

Instantly share code, notes, and snippets.

@felix-larsen
Created December 5, 2020 06:57
Show Gist options
  • Save felix-larsen/af7d8bda176f1e3772de465d69fbf3b3 to your computer and use it in GitHub Desktop.
Save felix-larsen/af7d8bda176f1e3772de465d69fbf3b3 to your computer and use it in GitHub Desktop.
5th December solution - Advent of Code - swift
let filename = "/Users/felix/xCodeProjects/AdventOfCode2020.playground/Resources/december05.txt"
let contents = try! String(contentsOfFile: filename)
let lines = contents.components(separatedBy: CharacterSet.newlines)
let seats = lines.compactMap { seatString -> Seat? in
if seatString.isEmpty {
return nil
}
let rowEndIndex = seatString.index(seatString.startIndex, offsetBy: 7)
let binaryRowString = String(seatString[..<rowEndIndex].map { (char) -> Character in
char == "B" ? "1" : "0"
})
let row = Int(binaryRowString, radix: 2)
let binaryColumnString = String(seatString[rowEndIndex...].map { (char) -> Character in
char == "R" ? "1" : "0"
})
let column = Int(binaryColumnString, radix: 2)
if let row = row, let column = column {
return Seat(row: row, column: column)
}
return nil
}
var seatIds = seats.map { $0.seatId }
print(seatIds.max())
seatIds.sort()
seatIds.reduce(seatIds.first! - 1) { (previousSeatId, currentSeatId) -> Int in
if previousSeatId + 1 != currentSeatId {
print(previousSeatId + 1)
}
return currentSeatId
}
struct Seat {
let row: Int
let column: Int
var seatId: Int {
get {
return row * 8 + column
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment