CoreAlgorithmTests.cs 13 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247
  1. using System;
  2. using System.Collections.Generic;
  3. using System.Linq;
  4. using DevilLink2.Core;
  5. using NUnit.Framework;
  6. namespace DevilLink2.Tests
  7. {
  8. public sealed class CoreAlgorithmTests
  9. {
  10. private readonly LinkPathFinder finder = new LinkPathFinder();
  11. [TestCase(8, 4)] [TestCase(8, 6)] [TestCase(14, 10)]
  12. public void GenerationFillsCellsWithUniqueIdsAndExpectedEvenSymbolCounts(int columns, int rows)
  13. {
  14. var board = BoardGenerator.Generate(columns, rows, 2026);
  15. var tiles = Tiles(board).ToArray();
  16. Assert.That(board.Columns, Is.EqualTo(columns));
  17. Assert.That(board.Rows, Is.EqualTo(rows));
  18. Assert.That(board.RemainingTileCount, Is.EqualTo(columns * rows));
  19. Assert.That(tiles.Select(t => t.Id).Distinct().Count(), Is.EqualTo(tiles.Length));
  20. for (int i = 0; i < tiles.Length; i++)
  21. {
  22. Assert.That(tiles[i].Row, Is.EqualTo(i / columns));
  23. Assert.That(tiles[i].Column, Is.EqualTo(i % columns));
  24. }
  25. foreach (TileSymbol symbol in Enum.GetValues(typeof(TileSymbol)))
  26. {
  27. int expectedPairs = Enumerable.Range(0, tiles.Length / 2).Count(i => i % 12 == (int)symbol);
  28. Assert.That(tiles.Count(t => t.Symbol == symbol), Is.EqualTo(expectedPairs * 2));
  29. }
  30. }
  31. [TestCase(8, 4)] [TestCase(8, 6)] [TestCase(14, 10)]
  32. public void SameSeedReproducesBoard(int columns, int rows)
  33. {
  34. Assert.That(Tiles(BoardGenerator.Generate(columns, rows, -7)).Select(t => t.Symbol),
  35. Is.EqualTo(Tiles(BoardGenerator.Generate(columns, rows, -7)).Select(t => t.Symbol)));
  36. }
  37. [Test]
  38. public void SymbolOrderMatchesSource()
  39. {
  40. Assert.That(Enum.GetNames(typeof(TileSymbol)), Is.EqualTo(new[]
  41. { "imp", "trident", "ring", "potion", "candle", "star", "piggy", "A", "Q", "J", "T10", "N9" }));
  42. }
  43. private sealed class ZeroRandom : Random
  44. {
  45. public readonly List<int> Bounds = new List<int>();
  46. public override int Next(int maxValue) { Bounds.Add(maxValue); return 0; }
  47. }
  48. [Test]
  49. public void FisherYatesUsesDescendingBoundsAndPreservesPermutation()
  50. {
  51. var values = new[] { 0, 1, 2, 3 }; var random = new ZeroRandom();
  52. BoardGenerator.Shuffle(values, random);
  53. Assert.That(random.Bounds, Is.EqualTo(new[] { 4, 3, 2 }));
  54. Assert.That(values, Is.EqualTo(new[] { 1, 2, 3, 0 }));
  55. BoardGenerator.Shuffle(new int[0], random);
  56. BoardGenerator.Shuffle(new[] { 5 }, random);
  57. Assert.That(random.Bounds.Count, Is.EqualTo(3));
  58. Assert.Throws<ArgumentNullException>(() => BoardGenerator.Shuffle<int>(null, random));
  59. Assert.Throws<ArgumentNullException>(() => BoardGenerator.Shuffle(values, null));
  60. }
  61. [TestCase(0, 4)] [TestCase(4, 0)] [TestCase(-1, 4)] [TestCase(3, 3)]
  62. [TestCase(int.MaxValue, 2)]
  63. public void InvalidGenerationIsRejected(int columns, int rows)
  64. { Assert.Catch<ArgumentException>(() => BoardGenerator.Generate(columns, rows, 0)); }
  65. [TestCase("AA", 0)] [TestCase("A.A", 0)]
  66. [TestCase("#####/#A..#/###.#/###A#/#####", 1)]
  67. [TestCase("#####/#A.##/##.##/##.A#/#####", 2)]
  68. [TestCase("A#A", 2)] [TestCase("A/#/A", 2)]
  69. public void LegalPathsAreCompressedAndRespectObstacles(string layout, int turns)
  70. {
  71. var board = Layout(layout); var ends = Tiles(board).Where(t => t.Symbol == TileSymbol.imp).ToArray();
  72. int count = board.RemainingTileCount;
  73. Assert.That(finder.TryFindPath(board, ends[0].Position, ends[1].Position, out var path), Is.True);
  74. Assert.That(path.Count - 2, Is.EqualTo(turns));
  75. ValidatePath(board, ends[0].Position, ends[1].Position, path);
  76. Assert.That(board.RemainingTileCount, Is.EqualTo(count));
  77. }
  78. [TestCase("#####/#A.##/##..#/###A#/#####")] // Three forced turns; endpoints cannot reach the border.
  79. [TestCase("#####/#A#A#/#####")] // Blocked straight route and no escape.
  80. public void ThreeTurnsOrBlockingWallsFail(string layout)
  81. {
  82. var board = Layout(layout); var ends = Tiles(board).Where(t => t.Symbol == TileSymbol.imp).ToArray();
  83. Assert.That(finder.TryFindPath(board, ends[0].Position, ends[1].Position, out var path), Is.False);
  84. Assert.That(path, Is.Empty);
  85. }
  86. [Test]
  87. public void InvalidEndpointsFailIncludingOutsideTheSingleBorder()
  88. {
  89. var board = Layout("A.#A");
  90. Assert.That(finder.TryFindPath(board, new GridPosition(0, 0), new GridPosition(0, 2), out _), Is.False);
  91. Assert.That(finder.TryFindPath(board, new GridPosition(0, 0), new GridPosition(0, 0), out _), Is.False);
  92. Assert.That(finder.TryFindPath(board, new GridPosition(0, 0), new GridPosition(0, 1), out _), Is.False);
  93. foreach (var p in new[] { new GridPosition(-2, 0), new GridPosition(2, 0),
  94. new GridPosition(0, -2), new GridPosition(0, 5), new GridPosition(-1, 0), new GridPosition(0, 4) })
  95. Assert.That(finder.TryFindPath(board, new GridPosition(0, 0), p, out _), Is.False);
  96. Assert.Throws<ArgumentNullException>(() => finder.TryFindPath(null, new GridPosition(0, 0), new GridPosition(0, 1), out _));
  97. }
  98. [Test]
  99. public void RemovalIsSafeAndDoesNotRefillOrRemoveForeignTiles()
  100. {
  101. var board = Layout("AA"); var tile = board.GetTile(0, 0);
  102. Assert.That(board.RemoveTile(new Tile(tile.Id, tile.Symbol, 0, 0)), Is.False);
  103. Assert.That(board.RemoveTile(tile), Is.True);
  104. Assert.That(board.IsEmpty(0, 0), Is.True);
  105. Assert.That(board.RemoveTile(tile), Is.False);
  106. Assert.That(board.RemoveTile(0, 0), Is.False);
  107. Assert.That(board.RemainingTileCount, Is.EqualTo(1));
  108. Assert.That(board.GetTile(0, 1), Is.Not.Null);
  109. Assert.That(finder.TryFindPath(board, tile.Position, new GridPosition(0, 1), out _), Is.False);
  110. Assert.That(board.RemoveTile(0, 1), Is.True);
  111. Assert.That(board.RemainingTileCount, Is.Zero);
  112. }
  113. [TestCase(-1, 0)] [TestCase(0, -1)] [TestCase(2, 0)] [TestCase(0, 2)]
  114. public void BoardAccessAndRemovalRejectOutOfBounds(int row, int column)
  115. {
  116. var board = Layout("AA/AA");
  117. Assert.Throws<ArgumentOutOfRangeException>(() => board.GetTile(row, column));
  118. Assert.Throws<ArgumentOutOfRangeException>(() => board.IsEmpty(row, column));
  119. Assert.Throws<ArgumentOutOfRangeException>(() => board.RemoveTile(row, column));
  120. Assert.That(board.RemainingTileCount, Is.EqualTo(4));
  121. }
  122. [Test]
  123. public void InvalidLayoutsAndTilesAreRejected()
  124. {
  125. Assert.Throws<ArgumentException>(() => new Board(2, 1, new[] { new Tile(1, TileSymbol.imp, 0, 0), new Tile(1, TileSymbol.ring, 0, 1) }));
  126. Assert.Throws<ArgumentException>(() => new Board(2, 1, new[] { new Tile(1, TileSymbol.imp, 0, 0), new Tile(2, TileSymbol.ring, 0, 0) }));
  127. Assert.Throws<ArgumentOutOfRangeException>(() => new Board(2, 1, new[] { new Tile(1, TileSymbol.imp, 1, 0) }));
  128. Assert.Throws<ArgumentNullException>(() => new Board(2, 1, null));
  129. Assert.Throws<ArgumentException>(() => new Board(2, 1, new Tile[] { null }));
  130. Assert.Throws<ArgumentOutOfRangeException>(() => new Tile(0, TileSymbol.imp, 0, 0));
  131. Assert.Throws<ArgumentOutOfRangeException>(() => new Tile(1, (TileSymbol)99, 0, 0));
  132. }
  133. [Test]
  134. public void ExhaustiveSmallBoardsAgreeWithIndependentCornerEnumeration()
  135. {
  136. // Every pair of endpoints and every obstacle mask on a 3x2 board: 240 layouts.
  137. for (int a = 0; a < 6; a++) for (int b = a + 1; b < 6; b++)
  138. for (int mask = 0; mask < 16; mask++)
  139. {
  140. var tiles = new List<Tile>(); int bit = 0;
  141. for (int i = 0; i < 6; i++)
  142. {
  143. if (i == a || i == b) tiles.Add(new Tile(i + 1, TileSymbol.imp, i / 3, i % 3));
  144. else if ((mask & (1 << bit++)) != 0) tiles.Add(new Tile(i + 1, TileSymbol.ring, i / 3, i % 3));
  145. }
  146. var board = new Board(3, 2, tiles);
  147. var start = new GridPosition(a / 3, a % 3); var end = new GridPosition(b / 3, b % 3);
  148. bool actual = finder.TryFindPath(board, start, end, out var path);
  149. Assert.That(actual, Is.EqualTo(CornerOracle(board, start, end)), $"a={a}, b={b}, mask={mask}");
  150. if (actual) ValidatePath(board, start, end, path);
  151. }
  152. }
  153. [Test]
  154. public void RandomInteriorLayoutsAgreeWithCornerOracleInBothDirections()
  155. {
  156. var random = new Random(87031);
  157. for (int sample = 0; sample < 600; sample++)
  158. {
  159. int a = random.Next(25), b;
  160. do { b = random.Next(25); } while (a == b);
  161. var tiles = new List<Tile>();
  162. for (int i = 0; i < 25; i++)
  163. {
  164. if (i == a || i == b) tiles.Add(new Tile(i + 1, TileSymbol.imp, i / 5, i % 5));
  165. else if (random.Next(100) < 65) tiles.Add(new Tile(i + 1, TileSymbol.ring, i / 5, i % 5));
  166. }
  167. var board = new Board(5, 5, tiles);
  168. var start = new GridPosition(a / 5, a % 5); var end = new GridPosition(b / 5, b % 5);
  169. bool expected = CornerOracle(board, start, end);
  170. Assert.That(finder.TryFindPath(board, start, end, out var path), Is.EqualTo(expected), $"sample={sample}");
  171. if (expected) ValidatePath(board, start, end, path);
  172. Assert.That(finder.TryFindPath(board, end, start, out var reverse), Is.EqualTo(expected));
  173. if (expected) ValidatePath(board, end, start, reverse);
  174. Assert.That(board.RemainingTileCount, Is.EqualTo(tiles.Count));
  175. }
  176. }
  177. private static IEnumerable<Tile> Tiles(Board board)
  178. {
  179. for (int r = 0; r < board.Rows; r++) for (int c = 0; c < board.Columns; c++)
  180. if (!board.IsEmpty(r, c)) yield return board.GetTile(r, c);
  181. }
  182. private static Board Layout(string layout)
  183. {
  184. var rows = layout.Split('/'); var tiles = new List<Tile>(); int id = 0;
  185. for (int r = 0; r < rows.Length; r++) for (int c = 0; c < rows[0].Length; c++)
  186. if (rows[r][c] != '.') tiles.Add(new Tile(++id, rows[r][c] == 'A' ? TileSymbol.imp : TileSymbol.ring, r, c));
  187. return new Board(rows[0].Length, rows.Length, tiles);
  188. }
  189. private static bool Segment(Board board, GridPosition a, GridPosition b, GridPosition start, GridPosition end)
  190. {
  191. if (a.Row != b.Row && a.Column != b.Column) return false;
  192. int dr = Math.Sign(b.Row - a.Row), dc = Math.Sign(b.Column - a.Column);
  193. var p = a;
  194. while (true)
  195. {
  196. if (p.Row < -1 || p.Row > board.Rows || p.Column < -1 || p.Column > board.Columns) return false;
  197. if (p != start && p != end && board.Contains(p.Row, p.Column) && !board.IsEmpty(p.Row, p.Column)) return false;
  198. if (p == b) return true;
  199. p = new GridPosition(p.Row + dr, p.Column + dc);
  200. }
  201. }
  202. private static bool CornerOracle(Board board, GridPosition a, GridPosition b)
  203. {
  204. // Enumerate straight paths and all possible horizontal/vertical middle segments.
  205. if (Segment(board, a, b, a, b)) return true;
  206. for (int r = -1; r <= board.Rows; r++)
  207. {
  208. var x = new GridPosition(r, a.Column); var y = new GridPosition(r, b.Column);
  209. if (Segment(board, a, x, a, b) && Segment(board, x, y, a, b) && Segment(board, y, b, a, b)) return true;
  210. }
  211. for (int c = -1; c <= board.Columns; c++)
  212. {
  213. var x = new GridPosition(a.Row, c); var y = new GridPosition(b.Row, c);
  214. if (Segment(board, a, x, a, b) && Segment(board, x, y, a, b) && Segment(board, y, b, a, b)) return true;
  215. }
  216. return false;
  217. }
  218. private static void ValidatePath(Board board, GridPosition start, GridPosition end, IReadOnlyList<GridPosition> path)
  219. {
  220. Assert.That(path.Count, Is.InRange(2, 4));
  221. Assert.That(path[0], Is.EqualTo(start)); Assert.That(path[path.Count - 1], Is.EqualTo(end));
  222. for (int i = 1; i < path.Count; i++)
  223. {
  224. Assert.That(path[i], Is.Not.EqualTo(path[i - 1]));
  225. Assert.That(Segment(board, path[i - 1], path[i], start, end), Is.True);
  226. if (i < path.Count - 1)
  227. Assert.That(path[i - 1].Row == path[i].Row && path[i].Row == path[i + 1].Row ||
  228. path[i - 1].Column == path[i].Column && path[i].Column == path[i + 1].Column, Is.False);
  229. }
  230. }
  231. }
  232. }