1
0
Fork 0
advent-of-code/2021/day7.cs

39 lines
948 B
C#
Raw Normal View History

2024-02-08 09:55:40 +01:00
using var sr = new StreamReader("../input/day7.txt");
var lines = sr.ReadToEnd().Split("\n").Select(x => x.Trim()).ToList();
var numbers = lines.First().Split(",").Select(double.Parse).ToList();
var acc = 0.0;
var median = GetMedian(numbers.ToArray());
foreach (var num in numbers)
acc += Math.Abs(num - median);
Console.WriteLine(acc);
acc = 0.0;
var avg = Math.Floor(numbers.Average());
foreach (var num in numbers)
{
var n = Math.Abs(num - avg);
acc += n * (n + 1) / 2; // Gauss formula, one of the very very few math tricks i know
}
Console.WriteLine(acc);
double GetMedian(double[] nums)
{
var ret = 0.0;
Array.Sort(nums);
if (nums.Length % 2 == 0)
{
var firstValue = nums[(nums.Length / 2) - 1];
var secondValue = nums[(nums.Length / 2)];
ret = (firstValue + secondValue) / 2.0;
}
if (nums.Length % 2 == 1)
{
ret = nums[(nums.Length / 2)];
}
return ret;
}