diff --git a/day4.chpl b/day4.chpl new file mode 100644 index 0000000..fbeb58d --- /dev/null +++ b/day4.chpl @@ -0,0 +1,14 @@ +use IO; + +iter pairs() { + var low1, low2, high1, high2 : int; + while readf("%i-%i,%i-%i", low1, high1, low2, high2) do + yield (low1..high1, low2..high2); +} + +proc anyContains((r1, r2): 2*range) { return r1.contains(r2) || r2.contains(r1); } +proc overlap((r1, r2): 2*range) { return !r1[r2].isEmpty(); } + +var thePairs = pairs(); +writeln(+ reduce anyContains(thePairs)); +writeln(+ reduce overlap(thePairs)); diff --git a/day4.cr b/day4.cr new file mode 100644 index 0000000..ddc71b6 --- /dev/null +++ b/day4.cr @@ -0,0 +1,38 @@ +require "advent" + +struct Range(B, E) + def contains?(other) + other.begin >= self.begin && other.end <= self.end + end + + def overlaps?(other) + these = self.to_a + others = other.to_a + these.any? { |i| others.includes? i } + end +end + +INPUT = input(2022, 4).lines.map do |line| + first, second = line.split(",").map do |str| + left, right = str.split("-").map &.to_i64 + left..right + end + {first, second} +end + +def part1(input) + input.count do |pair| + l, r = pair + l.contains?(r) || r.contains?(l) + end +end + +def part2(input) + input.count do |pair| + l, r = pair + l.overlaps?(r) + end +end + +puts part1(INPUT.clone) +puts part2(INPUT.clone)