This commit is contained in:
2024-12-12 13:13:17 -08:00
parent 423632525d
commit cd945d2456
4 changed files with 1056 additions and 0 deletions

21
day02/d02p1.swift Normal file
View File

@@ -0,0 +1,21 @@
import Foundation
func readInput(filePath: String) -> [[Int?]]? {
let content = try? String(contentsOfFile: filePath, encoding: .ascii)
let lines = content?.split(separator: "\n")
return lines?.map { $0.split(separator: " ").map { Int($0) } }
}
func check(_ report: [Int?]) -> Bool? {
if report.contains(nil) {
return nil
}
let diffs = zip(report.dropFirst(), report).map { $0.0! - $0.1! }
return diffs.allSatisfy { abs($0) >= 1 }
&& diffs.allSatisfy { abs($0) <= 3 }
&& (diffs.allSatisfy { $0 > 0 } || diffs.allSatisfy { 0 > $0 })
}
let reports = readInput(filePath: CommandLine.arguments[1])
let answer = reports!.compactMap(check).reduce(0, {n, x in x ? n+1 : n})
print(answer)

29
day02/d02p2.swift Normal file
View File

@@ -0,0 +1,29 @@
import Foundation
func readInput(filePath: String) -> [[Int?]]? {
let content = try? String(contentsOfFile: filePath, encoding: .ascii)
let lines = content?.split(separator: "\n")
return lines?.map { $0.split(separator: " ").map { Int($0) } }
}
func safe(_ report: [Int?]) -> Bool {
if report.contains(nil) {
return false
}
let diffs = zip(report.dropFirst(), report).map { $0.0! - $0.1! }
return diffs.allSatisfy { abs($0) >= 1 }
&& diffs.allSatisfy { abs($0) <= 3 }
&& (diffs.allSatisfy { $0 > 0 } || diffs.allSatisfy { 0 > $0 })
}
func drop<T>(_ l: [T], at: Int) -> [T] {
return l.enumerated().filter { $0.0 != at }.map { $0.1 }
}
func mutate<T>(_ l: [T]) -> [[T]] {
return (0..<l.count).map { drop(l, at: $0) }
}
let reports = readInput(filePath: CommandLine.arguments[1])
let answer = reports!.map(mutate).filter { $0.contains(where: safe) }.count
print(answer)

1000
day02/input.txt Normal file

File diff suppressed because it is too large Load Diff

6
day02/test.txt Normal file
View File

@@ -0,0 +1,6 @@
7 6 4 2 1
1 2 7 8 9
9 7 6 2 1
1 3 2 4 5
8 6 4 4 1
1 3 6 7 9