Skip to content

Instantly share code, notes, and snippets.

@bogren
Created December 11, 2020 16:20
Show Gist options
  • Save bogren/b231a7fe9473792c44f5daba3ea997e8 to your computer and use it in GitHub Desktop.
Save bogren/b231a7fe9473792c44f5daba3ea997e8 to your computer and use it in GitHub Desktop.
import Foundation
let data = try
String(contentsOfFile: "input", encoding: .utf8)
.components(separatedBy: .newlines)
struct Seat: Hashable {
let row: Int
let col: Int
init(_ row: Int, _ col: Int) {
self.row = row
self.col = col
}
func hash(into hasher: inout Hasher) {
hasher.combine(row)
hasher.combine(col)
}
static func ==(lhs: Seat, rhs: Seat) -> Bool {
return lhs.row == rhs.row && lhs.col == rhs.col
}
var adjacent: [Seat] {
return [
Seat(row-1, col-1),
Seat(row-1, col),
Seat(row-1, col+1),
Seat(row, col-1),
Seat(row, col+1),
Seat(row+1, col-1),
Seat(row+1, col),
Seat(row+1, col+1),
]
}
var
}
var floorplan = [Seat: Bool]()
for (i, d) in data.enumerated() {
for (j, x) in Array(d).enumerated() {
let seat = Seat(i, j)
if x == "L" {
floorplan[seat] = false
}
}
}
func simulate(_ floor: [Seat: Bool]) -> [Seat: Bool] {
var simulation = [Seat: Bool]()
for (seat, _) in floor {
var count = 0
for adj in seat.adjacent {
if let occupied = floor[adj] {
count += occupied ? 1 : 0
}
}
var status = floor[seat]
if status == false && count == 0 {
status = true
}
if status == true && count >= 4 {
status = false
}
simulation[seat] = status
}
return simulation
}
func solve1(_ floor: [Seat: Bool]) -> Int {
let next = simulate(floor)
if floor == next {
return next.values.filter { $0 == true }.count
}
return solve1(next)
}
let result = solve1(floorplan)
print(result)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment