Skip to content

Commit

Permalink
Add 2024, day 2, part 1
Browse files Browse the repository at this point in the history
  • Loading branch information
danielctull committed Dec 2, 2024
1 parent 2f7958b commit 12c4f29
Show file tree
Hide file tree
Showing 2 changed files with 33 additions and 8 deletions.
29 changes: 23 additions & 6 deletions Year2024/Sources/Day02.swift
Original file line number Diff line number Diff line change
Expand Up @@ -11,15 +11,32 @@ public enum Day02: Day {
.split(whereSeparator:(\.isWhitespace))
.map(Int.init)

let differences = zip(values, values.dropFirst())
.map(-)

return differences.map(abs).allSatisfy { $0 < 4 }
&& differences.map(\.signum).allSame
return check(differences(values))
}
}

public static func part2(_ input: Input) throws -> Int {
0
try input.lines.count {
let values = try $0
.split(whereSeparator:(\.isWhitespace))
.map(Int.init)

if check(differences(values)) { return true }

return (0..<values.count).contains { index in
var new = values
new.remove(at: index)
return check(differences(new))
}
}
}
}

fileprivate func differences(_ values: [Int]) -> [Int] {
zip(values.dropFirst(), values).map(-)
}

fileprivate func check(_ differences: [Int]) -> Bool {
differences.map(abs).allSatisfy { 0 < $0 && $0 < 4 }
&& differences.map(\.signum).allSame
}
12 changes: 10 additions & 2 deletions Year2024/Tests/Day02Tests.swift
Original file line number Diff line number Diff line change
Expand Up @@ -22,11 +22,19 @@ final class Day02Tests: XCTestCase {
}

func testPart2Examples() throws {
XCTAssertEqual(try Day02.part2([]), 0)
XCTAssertEqual(try Day02.part2([
"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",
]), 4)

}

func testPart2Puzzle() throws {
let input = try Bundle.module.input(named: "Day02")
XCTAssertEqual(try Day02.part2(input), 0)
XCTAssertEqual(try Day02.part2(input), 354)
}
}

0 comments on commit 12c4f29

Please sign in to comment.