Skip to content

Commit

Permalink
day 5 part 2
Browse files Browse the repository at this point in the history
  • Loading branch information
KaterynaKateryna committed Dec 6, 2024
1 parent a9e535b commit e4ad71f
Showing 1 changed file with 45 additions and 1 deletion.
46 changes: 45 additions & 1 deletion AdventOfCode/Day05.cs
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,18 @@ public override ValueTask<string> Solve_1()

public override ValueTask<string> Solve_2()
{
return new("");
int result = 0;
foreach (var update in updates)
{
if (!IsCorrectOrder(update))
{
Sort(update, 0, update.Count - 1);
int middle = update.Skip(update.Count / 2).First();
result += middle;
}
}

return new(result.ToString());
}

private bool IsCorrectOrder(List<int> update)
Expand Down Expand Up @@ -86,4 +97,37 @@ private bool IsCorrectOrder(List<int> update)

return true;
}

private void Sort(List<int> update, int leftIndex, int rightIndex)
{
if (leftIndex >= rightIndex
|| leftIndex < 0
|| leftIndex >= update.Count
|| rightIndex < 0
|| rightIndex >= update.Count
)
{
return;
}

int pivotIndex = leftIndex;
int pivot = update[leftIndex];

rulesReversed.TryGetValue(pivot, out List<int> haveToBeToTheLeft);

for (int i = leftIndex + 1; i <= rightIndex; i++)
{
int current = update[i];
if (haveToBeToTheLeft.Contains(current))
{
update.RemoveAt(i);
update.Insert(pivotIndex, current);
pivotIndex++;
i--;
}
}

Sort(update, leftIndex, pivotIndex-1);
Sort(update, pivotIndex + 1, rightIndex);
}
}

0 comments on commit e4ad71f

Please sign in to comment.