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.

MrvNextCellChooser.cs 2.1KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  1. using System.Collections.Generic;
  2. using uqac_ia_sudoku_csp.Interfaces;
  3. namespace uqac_ia_sudoku_csp.Solver.NextValueChoosers
  4. {
  5. public class MrvNextCellChooser : INextCellChooser
  6. {
  7. private readonly INextCellChooser _nextCellChooser;
  8. public MrvNextCellChooser(INextCellChooser nextCellChooser)
  9. {
  10. _nextCellChooser = nextCellChooser;
  11. }
  12. public void SelectVariable(Board board, out int x, out int y, IList<IConstraint> constraints)
  13. {
  14. var avail = 1;
  15. var vars = new List<KeyValuePair<int, int>>();
  16. while (avail <= board.Size && vars.Count == 0)
  17. {
  18. for (var xx = 0; xx < board.Size; ++xx)
  19. {
  20. for (var yy = 0; yy < board.Size; ++yy)
  21. {
  22. if (board.GetNumber(xx, yy) == null)
  23. {
  24. var remaining = GetRemainingValue(board, xx, yy, constraints);
  25. if (remaining == avail)
  26. {
  27. vars.Add(new KeyValuePair<int, int>(xx, yy));
  28. }
  29. }
  30. }
  31. }
  32. ++avail;
  33. }
  34. if (vars.Count == 0)
  35. {
  36. x = -1;
  37. y = -1;
  38. }
  39. else if (vars.Count == 1 || _nextCellChooser == null)
  40. {
  41. x = vars[0].Key;
  42. y = vars[0].Value;
  43. }
  44. else
  45. {
  46. _nextCellChooser.SelectVariable(board, out x, out y, constraints);
  47. }
  48. }
  49. protected int GetRemainingValue(Board board, int x, int y, IList<IConstraint> constraints)
  50. {
  51. var c = 0;
  52. for (var i = 0; i < board.Size; ++i)
  53. {
  54. board.SetNumber(x, y, i);
  55. if (board.IsConsistent(x, y, constraints))
  56. {
  57. ++c;
  58. }
  59. }
  60. board.ClearNumber(x, y);
  61. return c;
  62. }
  63. }
  64. }