AdventOfCode/Utils/Extensions/MathExtensions.cs

60 lines
1.2 KiB
C#
Raw Permalink Normal View History

2023-06-11 18:36:02 +00:00
namespace AdventOfCode.Utils.Extensions;
public static class MathExtensions
{
public static int Signal(this int x)
{
return x switch
{
< 0 => -1,
> 0 => 1,
_ => 0
};
}
public static bool IsDigit(this string s)
{
try
{
Convert.ToInt32(s);
}
2023-06-24 21:26:39 +00:00
catch (FormatException)
2023-06-11 18:36:02 +00:00
{
return false;
}
return true;
}
public static ulong ProductOfMax(this List<ulong> list, int maxCount)
{
2023-06-24 21:26:39 +00:00
var maxList = new List<ulong>(maxCount);
2023-06-11 18:36:02 +00:00
2023-06-24 21:26:39 +00:00
foreach (var number in list)
2023-06-11 18:36:02 +00:00
{
if (maxList.Count < maxList.Capacity)
2023-06-24 21:26:39 +00:00
{
2023-06-11 18:36:02 +00:00
maxList.Add(number);
2023-06-24 21:26:39 +00:00
}
else if (number > maxList.Min())
2023-06-11 18:36:02 +00:00
{
maxList.RemoveAt(0);
maxList.Add(number);
}
2023-06-24 21:26:39 +00:00
2023-06-11 18:36:02 +00:00
maxList.Sort();
}
ulong product = 1;
2023-06-24 21:26:39 +00:00
maxList.ForEach(n => product *= n);
2023-06-11 18:36:02 +00:00
return product;
}
public static int LeastCommonMultiplier(this List<int> list)
{
2023-06-24 21:26:39 +00:00
var lcm = 1;
foreach (var i in list)
2023-06-11 18:36:02 +00:00
lcm *= i / MathTools.GreatCommonDivider(lcm, i);
return lcm;
}
}