Skip to content

Commit

Permalink
recursion to loop
Browse files Browse the repository at this point in the history
  • Loading branch information
mazharenko committed Dec 18, 2024
1 parent 42502e4 commit 5a23aa8
Showing 1 changed file with 24 additions and 19 deletions.
43 changes: 24 additions & 19 deletions src/aoc/Common/Bfs/Folder.cs
Original file line number Diff line number Diff line change
Expand Up @@ -12,27 +12,32 @@ public TRes Run()
return Fold(seed, visited, queue);
}

private TRes Fold(TRes state, HashSet<TKey?> visited, PriorityQueue<Path<T>,int> queue)
private TRes Fold(TRes state, HashSet<TKey?> visited, PriorityQueue<Path<T>, int> queue)
{
if (queue.Count == 0)
return state;
var currentPath = queue.Dequeue();
var current = currentPath.PathList.Head;
switch (folder.Fold(state, currentPath))
while (true)
{
case (var newState, TraversalResult.Interrupt):
return newState;
case (var newState, TraversalResult.Continue):
var adjacent = adjacency.GetAdjacent(current.Item);
foreach (var (adjacentValue, weight) in adjacent)
{
var key = visitedKey(adjacentValue);
if (key is null || visited.Add(key))
queue.Enqueue(new Path<T>(currentPath.PathList.Prepend(new PathItem<T>(adjacentValue, current.Len + weight))), weight);
}

return Fold(newState, visited, queue);
default: throw new InvalidOperationException();
if (queue.Count == 0) return state;
var currentPath = queue.Dequeue();
var current = currentPath.PathList.Head;
switch (folder.Fold(state, currentPath))
{
case (var newState, TraversalResult.Interrupt):
return newState;
case (var newState, TraversalResult.Continue):
var adjacent = adjacency.GetAdjacent(current.Item);
foreach (var (adjacentValue, weight) in adjacent)
{
var key = visitedKey(adjacentValue);
if (key is null || visited.Add(key)) queue.Enqueue(new Path<T>(currentPath.PathList.Prepend(new PathItem<T>(adjacentValue, current.Len + weight))), weight);
}

state = newState;
continue;
default:
throw new InvalidOperationException();
}

break;

Check warning on line 40 in src/aoc/Common/Bfs/Folder.cs

View workflow job for this annotation

GitHub Actions / build-and-run

Unreachable code detected

Check warning on line 40 in src/aoc/Common/Bfs/Folder.cs

View workflow job for this annotation

GitHub Actions / build-and-run

Unreachable code detected
}
}
}
Expand Down

0 comments on commit 5a23aa8

Please sign in to comment.