about summary refs log tree commit diff
diff options
context:
space:
mode:
authorBen Harris <ben@tilde.team>2021-12-03 13:25:50 -0500
committerBen Harris <ben@tilde.team>2021-12-03 13:25:50 -0500
commit28eb4378a2a7c1d636d5cb26526d428a1ee9c2a6 (patch)
tree4943697fb9d563fbed4b31184199fedca4dbace0
parent72e81981a349096c6925cf8b162f513ec9d32da0 (diff)
use BigInteger for large inputs
also don't calculate MostCommon inside .Where()
-rw-r--r--aoc2021/Day03.cs14
-rw-r--r--aoc2021/Extensions.cs21
2 files changed, 28 insertions, 7 deletions
diff --git a/aoc2021/Day03.cs b/aoc2021/Day03.cs
index 85e1c81..f8e18dc 100644
--- a/aoc2021/Day03.cs
+++ b/aoc2021/Day03.cs
@@ -25,8 +25,8 @@ public sealed class Day03 : Day
             e.Append(ones > l ? '0' : '1');
         }
 
-        var gamma   = Convert.ToInt32(g.ToString(), 2);
-        var epsilon = Convert.ToInt32(e.ToString(), 2);
+        var gamma   = g.ToString().BigIntegerFromBinaryString();
+        var epsilon = e.ToString().BigIntegerFromBinaryString();
 
         return $"{gamma * epsilon}";
     }
@@ -42,18 +42,20 @@ public sealed class Day03 : Day
         var i = 0;
         while (o.Count > 1)
         {
-            o = o.Where(r => r[i] == MostCommon(i, o)).ToList();
+            var most = MostCommon(i, o);
+            o = o.Where(r => r[i] == most).ToList();
             i++;
         }
-        var o2 = Convert.ToInt64(o.Single(), 2);
+        var o2 = o.Single().BigIntegerFromBinaryString();
 
         i = 0;
         while (c.Count > 1)
         {
-            c = c.Where(r => r[i] != MostCommon(i, c)).ToList();
+            var most = MostCommon(i, c);
+            c = c.Where(r => r[i] != most).ToList();
             i++;
         }
-        var co2 = Convert.ToInt64(c.Single(), 2);
+        var co2 = c.Single().BigIntegerFromBinaryString();
 
         return $"{o2 * co2}";
     }
diff --git a/aoc2021/Extensions.cs b/aoc2021/Extensions.cs
index 44202c4..84587a4 100644
--- a/aoc2021/Extensions.cs
+++ b/aoc2021/Extensions.cs
@@ -1,4 +1,6 @@
-namespace aoc2021;
+using System.Numerics;
+
+namespace aoc2021;
 
 public static class Extensions
 {
@@ -23,4 +25,21 @@ public static class Extensions
     /// <returns></returns>
     public static bool Contains(this Range range, int i) =>
         i >= range.Start.Value && i <= range.End.Value;
+    
+    /// <summary>
+    /// Creates a new BigInteger from a binary (Base2) string
+    /// <see href="https://gist.github.com/mjs3339/73042bc0e717f98796ee9fa131e458d4" />
+    /// </summary>
+    public static BigInteger BigIntegerFromBinaryString(this string binaryValue)
+    {
+        BigInteger res = 0;
+        if (binaryValue.Count(b => b == '1') + binaryValue.Count(b => b == '0') != binaryValue.Length) return res;
+        foreach (var c in binaryValue)
+        {
+            res <<= 1;
+            res += c == '1' ? 1 : 0;
+        }
+
+        return res;
+    }
 }