Files
advent-of-code-2024/05/PrintQueue/UpdateValidator.cs
T

71 lines
1.5 KiB
C#
Raw Normal View History

2024-12-05 23:10:08 -06:00
namespace PrintQueue;
class UpdateValidator
{
public readonly Dictionary<int, HashSet<int>> Graph = [];
public UpdateValidator(List<OrderRule> rules)
{
foreach (var rule in rules)
{
if (Graph.ContainsKey(rule.X) is false)
{
Graph.Add(rule.X, []);
}
if (Graph.ContainsKey(rule.Y) is false)
{
Graph.Add(rule.Y, []);
}
Graph[rule.X].Add(rule.Y);
}
}
2024-12-06 00:23:04 -06:00
2024-12-05 23:47:44 -06:00
public Update Sort(Update update)
{
var sortedUpdate = new Update(update.Pages.ToList());
2024-12-06 00:23:04 -06:00
2024-12-05 23:47:44 -06:00
while (Validate(sortedUpdate) is false)
{
for (var i = 0; i < sortedUpdate.Pages.Count - 1; i++)
{
var currentPage = sortedUpdate.Pages[i];
var nextPage = sortedUpdate.Pages[i + 1];
2024-12-06 00:23:04 -06:00
if (IsInOrder(currentPage, nextPage))
2024-12-05 23:47:44 -06:00
{
continue;
}
2024-12-06 00:23:04 -06:00
2024-12-05 23:47:44 -06:00
sortedUpdate.Pages[i] = nextPage;
sortedUpdate.Pages[i + 1] = currentPage;
}
}
2024-12-06 00:23:04 -06:00
2024-12-05 23:47:44 -06:00
return sortedUpdate;
}
2024-12-05 23:10:08 -06:00
public bool Validate(Update update)
{
var previousPages = new List<int>();
foreach (var page in update.Pages)
{
2024-12-06 00:23:04 -06:00
if (previousPages.Any(previousPage => IsInOrder(previousPage, page) is false))
2024-12-05 23:10:08 -06:00
{
2024-12-05 23:47:44 -06:00
return false;
2024-12-05 23:10:08 -06:00
}
2024-12-05 23:47:44 -06:00
2024-12-05 23:10:08 -06:00
previousPages.Add(page);
}
return true;
}
2024-12-05 23:47:44 -06:00
2024-12-06 00:23:04 -06:00
private bool IsInOrder(int previousPage, int futurePage)
2024-12-05 23:47:44 -06:00
{
return Graph.TryGetValue(previousPage, out var dependents) &&
2024-12-06 00:23:04 -06:00
dependents.Contains(futurePage);
2024-12-05 23:47:44 -06:00
}
2024-12-05 23:10:08 -06:00
}