You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

Board.cs 2.7KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113
  1. using System;
  2. using System.IO;
  3. using System.Linq;
  4. namespace uqac_ia_sudoku_csp
  5. {
  6. public class Board
  7. {
  8. public string Characters { get; }
  9. public int Size => Game.Length;
  10. protected int?[][] Game { get; set; }
  11. public Board(string characters)
  12. {
  13. Characters = characters;
  14. InitGame(characters.Length);
  15. Init((x, y) => null);
  16. }
  17. public Board(string characters, Func<int, int, int?> cb)
  18. {
  19. Characters = characters;
  20. InitGame(characters.Length);
  21. Init(cb);
  22. }
  23. public Board(Board other)
  24. {
  25. Characters = other.Characters;
  26. InitGame(other.Size);
  27. Init(other.GetNumber);
  28. }
  29. public Board Clone()
  30. {
  31. return new Board(this);
  32. }
  33. protected void InitGame(int size)
  34. {
  35. Game = new int?[size][];
  36. for (var y = 0; y < size; ++y)
  37. {
  38. Game[y] = new int?[size];
  39. }
  40. }
  41. public void Init(Func<int, int, int?> cb)
  42. {
  43. for (var y = 0; y < Size; ++y)
  44. {
  45. for (var x = 0; x < Size; ++x)
  46. {
  47. SetNumber(x, y, cb(x, y));
  48. }
  49. }
  50. }
  51. public char? GetCharacter(int? v)
  52. {
  53. return v == null ? null : (char?)Characters[v.Value];
  54. }
  55. public char? GetCharacter(int x, int y)
  56. {
  57. return GetCharacter(GetNumber(x, y));
  58. }
  59. public void SetCharacter(int x, int y, char? c)
  60. {
  61. SetNumber(x, y, c == null ? null : (char?)Characters.IndexOf(c.Value));
  62. }
  63. public int? GetNumber(int x, int y)
  64. {
  65. return Game[y][x];
  66. }
  67. public void SetNumber(int x, int y, int? value)
  68. {
  69. Game[y][x] = value;
  70. }
  71. public void ClearNumber(int x, int y)
  72. {
  73. SetNumber(x, y, null);
  74. }
  75. public bool IsComplete()
  76. {
  77. return !Game.Any(line => line.Any(cell => cell == null));
  78. }
  79. public void Print(TextWriter stream)
  80. {
  81. stream.WriteLine(Characters);
  82. stream.WriteLine(new string('-', Size + 2));
  83. foreach (var line in Game)
  84. {
  85. stream.Write('|');
  86. foreach (var cell in line)
  87. {
  88. var c = GetCharacter(cell);
  89. stream.Write(c ?? ' ');
  90. }
  91. stream.WriteLine('|');
  92. }
  93. stream.WriteLine(new string('-', Size + 2));
  94. }
  95. }
  96. }