index.js 2.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123
  1. let arr = [];
  2. let emptyX = [];
  3. let emptyY = [];
  4. let count = 0;
  5. solve = ()=>{
  6. getInputs();
  7. recurse(0);
  8. fillIn();
  9. }
  10. getInputs = ()=>{
  11. let tbody = document.querySelector("tbody");
  12. for(let row of tbody.children){
  13. rowArr = [];
  14. for(let td of row.children){
  15. let rowValue = td.children[0].value;
  16. if(rowValue === ""){
  17. rowArr.push(0);
  18. }else{
  19. rowArr.push(parseInt(rowValue));
  20. }
  21. }
  22. arr.push(rowArr);
  23. }
  24. //Make a note of all empty spots
  25. for(let y = 0; y < 9; y++){
  26. for(let x = 0; x < 9; x++){
  27. if(arr[y][x] === 0){
  28. emptyY.push(y);
  29. emptyX.push(x);
  30. }
  31. }
  32. }
  33. }
  34. recurse = (emptyIndex)=>{
  35. count++;
  36. if(emptyIndex === emptyX.length){
  37. return true;
  38. }
  39. for(let n = 1; n <= 9; n++){
  40. if(isValid(emptyY[emptyIndex], emptyX[emptyIndex], n)){
  41. arr[emptyY[emptyIndex]][emptyX[emptyIndex]] = n;
  42. let isDone = recurse(emptyIndex + 1);
  43. if(isDone){
  44. return true;
  45. }
  46. }
  47. }
  48. arr[emptyY[emptyIndex]][emptyX[emptyIndex]] = 0;
  49. }
  50. isValid = (y, x, n)=>{
  51. for(let y2 = 0; y2 < 9; y2++){
  52. if(arr[y2][x] === n){
  53. return false;
  54. }
  55. }
  56. for(let x2 = 0; x2 < 9; x2++){
  57. if(arr[y][x2] === n){
  58. return false;
  59. }
  60. }
  61. let squareInputs = [getArrForBox(y), getArrForBox(x)];
  62. for(let i of squareInputs[0]){
  63. for(let j of squareInputs[1]){
  64. if(arr[i][j] === n){
  65. return false;
  66. }
  67. }
  68. }
  69. return true;
  70. },
  71. getArrForBox = (coord)=>{
  72. let coords = [[0, 1, 2], [3, 4, 5], [6, 7, 8]];
  73. for(let set of coords){
  74. for(let num of set){
  75. if(num === coord){
  76. return set;
  77. }
  78. }
  79. }
  80. }
  81. fillIn = ()=>{
  82. let tbody = document.querySelector("tbody");
  83. for(let i = 0; i < 9; i++){
  84. let row = tbody.children[i];
  85. for(let j = 0; j < 9; j++){
  86. row.children[j].children[0].value = arr[i][j];
  87. }
  88. }
  89. }
  90. reset = ()=>{
  91. let tbody = document.querySelector("tbody");
  92. for(let row of tbody.children){
  93. for(let td of row.children){
  94. td.children[0].value = "";
  95. }
  96. }
  97. arr = [];
  98. emptyX = [];
  99. emptyY = [];
  100. count = 0;
  101. }
  102. document.getElementById("solve").onclick = ()=>{solve()};
  103. document.getElementById("reset").onclick = ()=>{reset()};