diff --git a/day02/d02p1.swift b/day02/d02p1.swift new file mode 100644 index 0000000..b01018e --- /dev/null +++ b/day02/d02p1.swift @@ -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) diff --git a/day02/d02p2.swift b/day02/d02p2.swift new file mode 100644 index 0000000..f6f33e2 --- /dev/null +++ b/day02/d02p2.swift @@ -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(_ l: [T], at: Int) -> [T] { + return l.enumerated().filter { $0.0 != at }.map { $0.1 } +} + +func mutate(_ l: [T]) -> [[T]] { + return (0..