Skip to content

Commit

Permalink
Added day 4 solutions
Browse files Browse the repository at this point in the history
  • Loading branch information
HarshilShah committed Dec 4, 2022
1 parent 2051b7c commit 6ec3f5a
Show file tree
Hide file tree
Showing 2 changed files with 43 additions and 1 deletion.
42 changes: 42 additions & 0 deletions 2022/Sources/2022/Day4.swift
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import Algorithms
import Collections
import Foundation

extension ClosedRange {
func contains(_ other: ClosedRange) -> Bool {
other.clamped(to: self) == other
}
}

struct Day4: Day {
var input: String

init(input: String) {
self.input = input
}

func partOne() -> String {
input
.split(separator: "\n")
.lazy
.map(parse)
.filter { $0.0.contains($0.1) || $0.1.contains($0.0) }
.count
.description
}

func partTwo() -> String {
input
.split(separator: "\n")
.lazy
.map(parse)
.filter { $0.0.overlaps($0.1) }
.count
.description
}

func parse(_ line: Substring) -> (ClosedRange<Int>, ClosedRange<Int>) {
let numbers = line.split(whereSeparator: { $0.isNumber == false }).map { Int($0)! }
return (numbers[0] ... numbers[1], numbers[2] ... numbers[3])
}
}
2 changes: 1 addition & 1 deletion 2022/Sources/2022/main.swift
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
import Foundation

typealias CurrentDay = Day3
typealias CurrentDay = Day4

let testInput = """
<Insert your test input here>
Expand Down

0 comments on commit 6ec3f5a

Please sign in to comment.