From 05c93390289f20b91db99efaee3996c186b415fe Mon Sep 17 00:00:00 2001 From: Stefan Forstenlechner Date: Thu, 23 Dec 2021 18:10:41 +0100 Subject: [PATCH] Day 22 simpler version --- Day22.cs | 46 +++++++++++++++++++++++++++++++++++++++++----- 1 file changed, 41 insertions(+), 5 deletions(-) diff --git a/Day22.cs b/Day22.cs index 98df5ee..b8a0bac 100644 --- a/Day22.cs +++ b/Day22.cs @@ -1,7 +1,6 @@ #define Day22 #if Day22 using System.Text.RegularExpressions; -using AoC2021; var regex = new Regex(@"(?on|off) x=(?-?\d+)\.\.(?-?\d+),y=(?-?\d+)\.\.(?-?\d+),z=(?-?\d+)\.\.(?-?\d+)"); @@ -10,12 +9,26 @@ var changes = File.ReadAllLines("day22/input") .Select(From) .ToList(); - PartOne(changes); PartTwo(changes); +PartTwoSimpler(changes); + +void PartTwoSimpler(List changes) { + var onCuboids = new List(); + + foreach (var change in changes) { + var newOnCuboids = onCuboids.Where(c => !c.Outside(change)).Select(c => c.CutCommonPart(change)).ToList(); + if (change.turnOn) { + onCuboids.Add(new Cuboid() {from = change.from, to = change.to, negative = false}); + } + onCuboids.AddRange(newOnCuboids); + } + + var total = onCuboids.Select(c => c.NumberOfCubes()).Sum(); + Console.WriteLine(total); +} void PartTwo(List changes) { - int i = 0; var onCuboids = new List(); foreach (var change in changes) { @@ -68,6 +81,8 @@ Change From(Match m) { record Change(bool turnOn, Point from, Point to); record Point(int x, int y, int z); class Cuboid { + + public bool negative { get; set; } // used for part two simpler version only public Point from { get; set; } public Point to { get; set; } @@ -77,7 +92,7 @@ class Cuboid { && change.from.z <= from.z && change.to.z >= to.z; } - bool Outside(Change change) { + public bool Outside(Change change) { return change.to.x < from.x || change.from.x > to.x || change.to.y < from.y || change.from.y > to.y || change.to.z < from.z || change.from.z > to.z; @@ -88,7 +103,8 @@ class Cuboid { long y = to.y - from.y + 1; long z = to.z - from.z + 1; - return x * y * z; + long total = x * y * z; + return negative ? -total : total; } public List Cut(Change change) { @@ -169,5 +185,25 @@ class Cuboid { return newCuboids; } + + public Cuboid CutCommonPart(Change change) { + if (Outside(change)) { + throw new Exception(); + } + + return new Cuboid() { + negative = !this.negative, + from = new Point( + Math.Max(from.x, change.from.x), + Math.Max(from.y, change.from.y), + Math.Max(from.z, change.from.z) + ), + to = new Point( + Math.Min(to.x, change.to.x), + Math.Min(to.y, change.to.y), + Math.Min(to.z, change.to.z) + ) + }; + } } #endif \ No newline at end of file