use BigInteger for large inputs
continuous-integration/drone/push Build is passing
Details
continuous-integration/drone/push Build is passing
Details
also don't calculate MostCommon inside .Where()
This commit is contained in:
parent
72e81981a3
commit
28eb4378a2
|
@ -25,8 +25,8 @@ public sealed class Day03 : Day
|
||||||
e.Append(ones > l ? '0' : '1');
|
e.Append(ones > l ? '0' : '1');
|
||||||
}
|
}
|
||||||
|
|
||||||
var gamma = Convert.ToInt32(g.ToString(), 2);
|
var gamma = g.ToString().BigIntegerFromBinaryString();
|
||||||
var epsilon = Convert.ToInt32(e.ToString(), 2);
|
var epsilon = e.ToString().BigIntegerFromBinaryString();
|
||||||
|
|
||||||
return $"{gamma * epsilon}";
|
return $"{gamma * epsilon}";
|
||||||
}
|
}
|
||||||
|
@ -42,18 +42,20 @@ public sealed class Day03 : Day
|
||||||
var i = 0;
|
var i = 0;
|
||||||
while (o.Count > 1)
|
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++;
|
i++;
|
||||||
}
|
}
|
||||||
var o2 = Convert.ToInt64(o.Single(), 2);
|
var o2 = o.Single().BigIntegerFromBinaryString();
|
||||||
|
|
||||||
i = 0;
|
i = 0;
|
||||||
while (c.Count > 1)
|
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++;
|
i++;
|
||||||
}
|
}
|
||||||
var co2 = Convert.ToInt64(c.Single(), 2);
|
var co2 = c.Single().BigIntegerFromBinaryString();
|
||||||
|
|
||||||
return $"{o2 * co2}";
|
return $"{o2 * co2}";
|
||||||
}
|
}
|
||||||
|
|
|
@ -1,4 +1,6 @@
|
||||||
namespace aoc2021;
|
using System.Numerics;
|
||||||
|
|
||||||
|
namespace aoc2021;
|
||||||
|
|
||||||
public static class Extensions
|
public static class Extensions
|
||||||
{
|
{
|
||||||
|
@ -23,4 +25,21 @@ public static class Extensions
|
||||||
/// <returns></returns>
|
/// <returns></returns>
|
||||||
public static bool Contains(this Range range, int i) =>
|
public static bool Contains(this Range range, int i) =>
|
||||||
i >= range.Start.Value && i <= range.End.Value;
|
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;
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
Loading…
Reference in New Issue