74 lines
2.7 KiB
C#
74 lines
2.7 KiB
C#
|
using System;
|
|||
|
using System.Collections;
|
|||
|
|
|||
|
namespace Advent24
|
|||
|
{
|
|||
|
internal class Program
|
|||
|
{
|
|||
|
static void Main(string[] args)
|
|||
|
{
|
|||
|
string fileData = System.IO.File.ReadAllText(@"..\..\..\inputd1.txt");
|
|||
|
var pairsArray = fileData.Split('\n');
|
|||
|
|
|||
|
var list1 = new SortedList<Int32, Int32>(pairsArray.Length);
|
|||
|
var list2 = new SortedList<Int32, Int32>(pairsArray.Length);
|
|||
|
foreach(var pair in pairsArray)
|
|||
|
{
|
|||
|
if (System.String.IsNullOrEmpty(pair)) continue;
|
|||
|
// pairArray has 4 elements, and the middle two are blanks
|
|||
|
// because there are 3 spaces between the two numbers
|
|||
|
var pairArray = pair.Split(' ');
|
|||
|
Int32 myInteger = System.Convert.ToInt32(pairArray[0]);
|
|||
|
if (list1.TryGetValue(myInteger, out int value1)) list1[myInteger] = ++value1;
|
|||
|
else list1.Add(myInteger, 1);
|
|||
|
Console.WriteLine("{0:d} {1:d}", myInteger, list1[myInteger]);
|
|||
|
|
|||
|
myInteger = System.Convert.ToInt32(pairArray[3]);
|
|||
|
if (list2.TryGetValue(myInteger, out int value2)) list2[myInteger] = ++value2;
|
|||
|
else list2.Add(myInteger, 1);
|
|||
|
Console.WriteLine("{0:d} {1:d}", myInteger, list2[myInteger]);
|
|||
|
}
|
|||
|
|
|||
|
Int32 sumOfDifferences = 0;
|
|||
|
Int32 i = 0, j = 0;
|
|||
|
|
|||
|
var list1Copy = new SortedList<Int32, Int32>(list1);
|
|||
|
var list2Copy = new SortedList<Int32, Int32>(list2);
|
|||
|
|
|||
|
while (i < list1.Count && j < list2.Count)
|
|||
|
{
|
|||
|
Int32 value1 = list1.GetKeyAtIndex(i);
|
|||
|
Int32 value2 = list2.GetKeyAtIndex(j);
|
|||
|
|
|||
|
if (value1 > value2) sumOfDifferences += (value1 - value2);
|
|||
|
else sumOfDifferences += (value2 - value1);
|
|||
|
|
|||
|
list1[value1]--; list2[value2]--;
|
|||
|
|
|||
|
if (list1[value1] == 0) i++;
|
|||
|
if (list2[value2] == 0) j++;
|
|||
|
}
|
|||
|
|
|||
|
Console.WriteLine("{0:s} {1:d}", "Sum of differences = ", sumOfDifferences);
|
|||
|
|
|||
|
i = 0; Int32 similarityScore = 0;
|
|||
|
while (i < list1Copy.Count)
|
|||
|
{
|
|||
|
Int32 value1 = list1Copy.GetKeyAtIndex(i);
|
|||
|
list2Copy.TryGetValue(value1, out Int32 numberOfAppearancesInList2);
|
|||
|
|
|||
|
// default value of Int32 numberOfAppearancesInList2 is 0
|
|||
|
similarityScore += value1 * numberOfAppearancesInList2;
|
|||
|
|
|||
|
list1Copy[value1]--;
|
|||
|
|
|||
|
if (list1Copy[value1] == 0) i++;
|
|||
|
}
|
|||
|
|
|||
|
Console.WriteLine("{0:s} {1:d}", "Similarity score = ", similarityScore);
|
|||
|
|
|||
|
Console.ReadLine();
|
|||
|
}
|
|||
|
}
|
|||
|
}
|