From 20c93249bb183773e3929a1afc34c11cec8f4803 Mon Sep 17 00:00:00 2001 From: Ben Harris Date: Sun, 4 Dec 2022 21:37:27 -0500 Subject: [PATCH] add some ext methods for Range --- AOC.Common/Extensions.cs | 21 ++++++++++++++++++++- AOC2022/Day04.cs | 17 +++++++---------- 2 files changed, 27 insertions(+), 11 deletions(-) diff --git a/AOC.Common/Extensions.cs b/AOC.Common/Extensions.cs index d0c80cc..f285db8 100644 --- a/AOC.Common/Extensions.cs +++ b/AOC.Common/Extensions.cs @@ -58,6 +58,25 @@ public static class Extensions public static bool Contains(this Range range, int i) => i >= range.Start.Value && i <= range.End.Value; + /// + /// Does contain the entire range of ? + /// + /// + /// + /// + public static bool Contains(this Range r1, Range r2) => + r1.Start.Value <= r2.Start.Value && r1.End.Value >= r2.End.Value; + + /// + /// Do and overlap? + /// + /// + /// + /// + public static bool Overlaps(this Range r1, Range r2) => + r1.Start.Value <= r2.End.Value && r1.End.Value >= r2.Start.Value && + r2.Start.Value <= r1.End.Value && r2.End.Value >= r1.Start.Value; + /// /// Creates a new BigInteger from a binary (Base2) string /// @@ -103,4 +122,4 @@ public static class Extensions public static IEnumerable> WhereValue( this IEnumerable> source, Func func) => source.Where(pair => func(pair.Value)); -} +} \ No newline at end of file diff --git a/AOC2022/Day04.cs b/AOC2022/Day04.cs index d686c6c..56cf0c8 100644 --- a/AOC2022/Day04.cs +++ b/AOC2022/Day04.cs @@ -5,22 +5,19 @@ namespace AOC2022; /// public sealed class Day04 : Day { - private readonly List> _ranges = new(); + private readonly List<(Range r1, Range r2)> _ranges; public Day04() : base(2022, 4, "Camp Cleanup") { - foreach (var line in Input) - _ranges.Add(line.Split(',').SelectMany(q => q.Split('-')).Select(int.Parse).ToList()); + _ranges = Input + .Select(line => line.Split(',').SelectMany(q => q.Split('-')).Select(int.Parse).ToList()) + .Select(p => (new Range(p[0], p[1]), new Range(p[2], p[3]))) + .ToList(); } public override object Part1() => - _ranges.Count(r => - (r[0] >= r[2] && r[0] <= r[3] && r[1] >= r[2] && r[1] <= r[3]) || - (r[2] >= r[0] && r[2] <= r[1] && r[3] >= r[0] && r[3] <= r[1])); + _ranges.Count(r => r.r1.Contains(r.r2) || r.r2.Contains(r.r1)); public override object Part2() => - _ranges.Count(r => (r[0] >= r[2] && r[0] <= r[3]) || - (r[1] >= r[2] && r[1] <= r[3]) || - (r[2] >= r[0] && r[2] <= r[1]) || - (r[3] >= r[0] && r[3] <= r[1])); + _ranges.Count(r => r.r1.Overlaps(r.r2)); } \ No newline at end of file