Skip to content

Commit 59e8f24

Browse files
committed
Updates the initialization of lists and dictionaries throughout the codebase
Add tests for `AStar` and related classes to validate A* algorithm functionality.
1 parent cc23e6b commit 59e8f24

File tree

34 files changed

+180
-66
lines changed

34 files changed

+180
-66
lines changed

Algorithms.Tests/Graph/BellmanFordTests.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -35,7 +35,7 @@ public void CorrectDistancesTest()
3535
{ vertex5, -4 }
3636
};
3737

38-
var bellmanFord = new BellmanFord<int>(graph, new Dictionary<Vertex<int>, double>(), new Dictionary<Vertex<int>, Vertex<int>?>());
38+
var bellmanFord = new BellmanFord<int>(graph, [], []);
3939

4040
var calculatedDistances = bellmanFord.Run(vertex1);
4141

@@ -61,7 +61,7 @@ public void NegativeWeightCycleTest()
6161
graph.AddEdge(vertex2, vertex3, -2);
6262
graph.AddEdge(vertex3, vertex1, -3);
6363

64-
var bellmanFord = new BellmanFord<int>(graph, new Dictionary<Vertex<int>, double>(), new Dictionary<Vertex<int>, Vertex<int>?>());
64+
var bellmanFord = new BellmanFord<int>(graph, [], []);
6565

6666
Action action = () => bellmanFord.Run(vertex1);
6767

Algorithms.Tests/Numeric/AutomorphicNumberTests.cs

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -55,21 +55,21 @@ public void TestInvalidAutomorphicNumbers(int number)
5555
[TestCase(1, 100)]
5656
public void TestAutomorphicNumberSequence(int lower, int upper)
5757
{
58-
List<long> automorphicList = new() { 1, 5, 6, 25, 76 };
58+
List<long> automorphicList = [1, 5, 6, 25, 76];
5959
Assert.That(AutomorphicNumber.GetAutomorphicNumbers(lower, upper), Is.EqualTo(automorphicList));
6060
}
6161

6262
[TestCase(8, 12)]
6363
public void TestNoAutomorphicNumberInTheSequence(int lower, int upper)
6464
{
65-
List<long> automorphicList = new();
65+
List<long> automorphicList = [];
6666
Assert.That(AutomorphicNumber.GetAutomorphicNumbers(lower, upper), Is.EqualTo(automorphicList));
6767
}
6868

6969
[TestCase(25, 25)]
7070
public void TestAutomorphicNumberSequenceSameBounds(int lower, int upper)
7171
{
72-
List<long> automorphicList = new() { 25 };
72+
List<long> automorphicList = [25];
7373
Assert.That(AutomorphicNumber.GetAutomorphicNumbers(lower, upper), Is.EqualTo(automorphicList));
7474
}
7575

Algorithms.Tests/Other/KochSnowflakeTest.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -8,7 +8,7 @@ public static class KochSnowflakeTest
88
[Test]
99
public static void TestIterateMethod()
1010
{
11-
List<Vector2> vectors = new() { new Vector2(0, 0), new Vector2(1, 0) };
11+
List<Vector2> vectors = [new Vector2(0, 0), new Vector2(1, 0)];
1212
List<Vector2> result = KochSnowflake.Iterate(vectors, 1);
1313
result[0].Should().Be(new Vector2(0, 0));
1414
result[1].Should().Be(new Vector2((float)1 / 3, 0));
Lines changed: 106 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,106 @@
1+
2+
using System.Reflection;
3+
4+
using Algorithms.Search.AStar;
5+
6+
namespace Algorithms.Tests.Search;
7+
8+
public static class AStarTests
9+
{
10+
[Test]
11+
public static void ResetNodes_ResetsAllNodeProperties()
12+
{
13+
var node = new Node(new VecN(0, 0), true, 1.0)
14+
{
15+
CurrentCost = 5,
16+
EstimatedCost = 10,
17+
Parent = new Node(new VecN(1, 1), true, 1.0),
18+
State = NodeState.Closed
19+
};
20+
var nodes = new List<Node> { node };
21+
22+
AStar.ResetNodes(nodes);
23+
24+
node.CurrentCost.Should().Be(0);
25+
node.EstimatedCost.Should().Be(0);
26+
node.Parent.Should().BeNull();
27+
node.State.Should().Be(NodeState.Unconsidered);
28+
}
29+
30+
[Test]
31+
public static void GeneratePath_ReturnsPathFromTargetToRoot()
32+
{
33+
var start = new Node(new VecN(0, 0), true, 1.0);
34+
var mid = new Node(new VecN(1, 0), true, 1.0) { Parent = start };
35+
var end = new Node(new VecN(2, 0), true, 1.0) { Parent = mid };
36+
37+
var path = AStar.GeneratePath(end);
38+
39+
path.Should().HaveCount(3);
40+
path[0].Should().BeSameAs(start);
41+
path[1].Should().BeSameAs(mid);
42+
path[2].Should().BeSameAs(end);
43+
}
44+
45+
[Test]
46+
public static void Compute_ReturnsEmptyList_WhenNoPathExists()
47+
{
48+
var start = new Node(new VecN(0, 0), true, 1.0);
49+
var end = new Node(new VecN(1, 0), true, 1.0);
50+
start.ConnectedNodes = [];
51+
end.ConnectedNodes = [];
52+
53+
var path = AStar.Compute(start, end);
54+
55+
path.Should().BeEmpty();
56+
}
57+
58+
[Test]
59+
public static void Compute_ReturnsPath_WhenPathExists()
60+
{
61+
var start = new Node(new VecN(0, 0), true, 1.0);
62+
var mid = new Node(new VecN(1, 0), true, 1.0);
63+
var end = new Node(new VecN(2, 0), true, 1.0);
64+
65+
start.ConnectedNodes = [mid];
66+
mid.ConnectedNodes = [end];
67+
end.ConnectedNodes = [];
68+
69+
var path = AStar.Compute(start, end);
70+
71+
path.Should().NotBeEmpty();
72+
path[0].Should().Be(start);
73+
path[^1].Should().Be(end);
74+
}
75+
76+
[Test]
77+
public static void VecN_Equality_WorksAsExpected()
78+
{
79+
var a = new VecN(1, 2);
80+
var b = new VecN(1, 2);
81+
var c = new VecN(2, 1);
82+
83+
a.Equals(b).Should().BeTrue();
84+
a.Equals(c).Should().BeFalse();
85+
}
86+
87+
[Test]
88+
public static void AddOrUpdateConnected_ThrowsPathfindingException_OnSelfReference()
89+
{
90+
var node = new Node(new VecN(0, 0), true, 1.0);
91+
node.ConnectedNodes = [node];
92+
node.State = NodeState.Open;
93+
94+
var queue = new PriorityQueue<Node>();
95+
96+
Action act = () => {
97+
// Directly call the private method using reflection, otherwise we can't test this case
98+
var method = typeof(AStar).GetMethod("AddOrUpdateConnected", BindingFlags.NonPublic | BindingFlags.Static);
99+
method!.Invoke(null, [node, node, queue]);
100+
};
101+
102+
act.Should().Throw<TargetInvocationException>()
103+
.WithInnerException<PathfindingException>()
104+
.WithMessage("*same node twice*");
105+
}
106+
}

Algorithms/Encoders/FeistelCipher.cs

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -118,7 +118,7 @@ public string Decode(string text, uint key)
118118
// the last block is extended up to 8 bytes if the tail of the text is smaller than 8 bytes
119119
private static List<ulong> SplitTextToBlocks(string text)
120120
{
121-
List<ulong> blocksListPlain = new();
121+
List<ulong> blocksListPlain = [];
122122
byte[] textArray = Encoding.ASCII.GetBytes(text);
123123
int offset = 8;
124124
for (int i = 0; i < text.Length; i += 8)
@@ -139,7 +139,7 @@ private static List<ulong> SplitTextToBlocks(string text)
139139
// convert the encoded text to the set of ulong values (blocks for decoding)
140140
private static List<ulong> GetBlocksFromEncodedText(string text)
141141
{
142-
List<ulong> blocksListPlain = new();
142+
List<ulong> blocksListPlain = [];
143143
for (int i = 0; i < text.Length; i += 16)
144144
{
145145
ulong block = Convert.ToUInt64(text.Substring(i, 16), 16);

Algorithms/Graph/BreadthFirstSearch.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class BreadthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
1818
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
1919
public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = default)
2020
{
21-
Bfs(graph, startVertex, action, new HashSet<Vertex<T>>());
21+
Bfs(graph, startVertex, action, []);
2222
}
2323

2424
/// <summary>

Algorithms/Graph/DepthFirstSearch.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -18,7 +18,7 @@ public class DepthFirstSearch<T> : IGraphSearch<T> where T : IComparable<T>
1818
/// <param name="action">Action that needs to be executed on each graph vertex.</param>
1919
public void VisitAll(IDirectedWeightedGraph<T> graph, Vertex<T> startVertex, Action<Vertex<T>>? action = default)
2020
{
21-
Dfs(graph, startVertex, action, new HashSet<Vertex<T>>());
21+
Dfs(graph, startVertex, action, []);
2222
}
2323

2424
/// <summary>

Algorithms/Graph/Kosaraju.cs

Lines changed: 4 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -74,9 +74,9 @@ public static void Assign(Vertex<T> v, Vertex<T> root, IDirectedWeightedGraph<T>
7474
/// <returns>A dictionary that assigns to each vertex a root vertex of the SCC they belong. </returns>
7575
public static Dictionary<Vertex<T>, Vertex<T>> GetRepresentatives(IDirectedWeightedGraph<T> graph)
7676
{
77-
HashSet<Vertex<T>> visited = new HashSet<Vertex<T>>();
77+
HashSet<Vertex<T>> visited = [];
7878
Stack<Vertex<T>> reversedL = new Stack<Vertex<T>>();
79-
Dictionary<Vertex<T>, Vertex<T>> representatives = new Dictionary<Vertex<T>, Vertex<T>>();
79+
Dictionary<Vertex<T>, Vertex<T>> representatives = [];
8080

8181
foreach (var v in graph.Vertices)
8282
{
@@ -105,7 +105,7 @@ public static Dictionary<Vertex<T>, Vertex<T>> GetRepresentatives(IDirectedWeigh
105105
public static IEnumerable<Vertex<T>>[] GetScc(IDirectedWeightedGraph<T> graph)
106106
{
107107
var representatives = GetRepresentatives(graph);
108-
Dictionary<Vertex<T>, List<Vertex<T>>> scc = new Dictionary<Vertex<T>, List<Vertex<T>>>();
108+
Dictionary<Vertex<T>, List<Vertex<T>>> scc = [];
109109
foreach (var kv in representatives)
110110
{
111111
// Assign all vertex (key) that have the seem root (value) to a single list.
@@ -115,7 +115,7 @@ public static IEnumerable<Vertex<T>>[] GetScc(IDirectedWeightedGraph<T> graph)
115115
}
116116
else
117117
{
118-
scc.Add(kv.Value, new List<Vertex<T>> { kv.Key });
118+
scc.Add(kv.Value, [kv.Key]);
119119
}
120120
}
121121

Algorithms/Graph/MinimumSpanningTree/Kruskal.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -108,7 +108,7 @@ public static Dictionary<int, float>[] Solve(Dictionary<int, float>[] adjacencyL
108108
var mst = new Dictionary<int, float>[numNodes];
109109
for (var i = 0; i < numNodes; i++)
110110
{
111-
mst[i] = new Dictionary<int, float>();
111+
mst[i] = [];
112112
}
113113

114114
foreach (var (node1, node2) in edges)

Algorithms/Knapsack/BranchAndBoundKnapsackSolver.cs

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -102,7 +102,7 @@ public T[] Solve(T[] items, int capacity, Func<T, int> weightSelector, Func<T, d
102102
// determine items taken based on the path
103103
private static T[] GetItemsFromPath(T[] items, BranchAndBoundNode lastNodeOfPath)
104104
{
105-
List<T> takenItems = new();
105+
List<T> takenItems = [];
106106

107107
// only bogus initial node has no parent
108108
for (var current = lastNodeOfPath; current.Parent is not null; current = current.Parent)

0 commit comments

Comments
 (0)