Skip to content

Commit

Permalink
Day 8
Browse files Browse the repository at this point in the history
  • Loading branch information
CraigSiemens committed Dec 9, 2023
1 parent aaa1e52 commit 5907cd8
Show file tree
Hide file tree
Showing 5 changed files with 854 additions and 2 deletions.
4 changes: 2 additions & 2 deletions Package.resolved
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@
"kind" : "remoteSourceControl",
"location" : "https://github.com/apple/swift-algorithms",
"state" : {
"revision" : "b14b7f4c528c942f121c8b860b9410b2bf57825e",
"version" : "1.0.0"
"revision" : "f6919dfc309e7f1b56224378b11e28bab5bccc42",
"version" : "1.2.0"
}
},
{
Expand Down
1 change: 1 addition & 0 deletions Sources/AdventOfCode2023/AdventOfCode2023.swift
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ public struct AdventOfCode2023: Year {
Day5(),
Day6(),
Day7(),
Day8(),
// {DAYS}
]

Expand Down
81 changes: 81 additions & 0 deletions Sources/AdventOfCode2023/Day8/Day8.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,81 @@
import Algorithms
import Foundation
import Utilities

public struct Day8: Day {
public func part1Solution(for input: Input) -> Int {
let parts = input.words(by: "\n\n")

let instructions = parts[0].characters

let map = parts[1]
.lines
.map { line in
line.words(by: CharacterSet.alphanumerics.inverted)
.map(\.raw)
}
.keyed { $0[0] }
.mapValues { (left: $0[1], right: $0[2]) }

var index = 0
var count = 0
var location = "AAA"
let end = "ZZZ"

while location != end {
let instruction = instructions[index]
if instruction == "L" {
location = map[location]!.left
} else if instruction == "R" {
location = map[location]!.right
} else {
fatalError("impossible")
}

index = (index + 1) % instructions.count
count += 1
}

return count
}

public func part2Solution(for input: Input) -> Int {
let parts = input.words(by: "\n\n")

let instructions = parts[0].characters

let map = parts[1]
.lines
.map { line in
line.words(by: CharacterSet.alphanumerics.inverted)
.map(\.raw)
}
.keyed { $0[0] }
.mapValues { (left: $0[1], right: $0[2]) }

return map.keys
.filter { $0.hasSuffix("A") }
.map { start in
var index = 0
var count = 0
var location = start

while !location.hasSuffix("Z") {
let instruction = instructions[index]
if instruction == "L" {
location = map[location]!.left
} else if instruction == "R" {
location = map[location]!.right
} else {
fatalError("impossible")
}

index = (index + 1) % instructions.count
count += 1
}

return count
}
.reduce(1) { $0.lcm(with: $1) }
}
}
Loading

0 comments on commit 5907cd8

Please sign in to comment.