-
Notifications
You must be signed in to change notification settings - Fork 84
/
sudokuJS.js
1816 lines (1518 loc) · 53.2 KB
/
sudokuJS.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
// sudokuJS v0.4.4
// https://github.com/pocketjoso/sudokuJS
// Author: Jonas Ohlsson
// License: MIT
(function (window, $, undefined) {
'use strict';
/*TODO:
--possible additions--
toggle edit candidates
undo/redo
*/
/**
* Define a jQuery plugin
*/
$.fn.sudokuJS = function(opts) {
/*
* constants
*-----------*/
var DIFFICULTY_EASY = "easy";
var DIFFICULTY_MEDIUM = "medium";
var DIFFICULTY_HARD = "hard";
var DIFFICULTY_VERY_HARD = "very hard";
var SOLVE_MODE_STEP = "step";
var SOLVE_MODE_ALL = "all";
var DIFFICULTIES = [
DIFFICULTY_EASY,
DIFFICULTY_MEDIUM,
DIFFICULTY_HARD,
DIFFICULTY_VERY_HARD
];
/*
* variables
*-----------*/
opts = opts || {};
var solveMode = SOLVE_MODE_STEP,
difficulty = "unknown",
candidatesShowing = false,
editingCandidates = false,
boardFinished = false,
boardError = false,
onlyUpdatedCandidates = false,
gradingMode = false, //solving without updating UI
generatingMode = false, //silence board unsolvable errors
invalidCandidates = [], //used by the generateBoard function
/*
the score reflects how much increased difficulty the board gets by having the pattern rather than an already solved cell
*/
strategies = [
{title: "openSingles", fn: openSingles, score : 0.1 },
//harder for human to spot
{title: "singleCandidate", fn: singleCandidate, score : 9 },
{title: "visualElimination", fn: visualElimination, score : 8 },
//only eliminates one candidate, should have lower score?
{title: "nakedPair", fn: nakedPair, score : 50 },
{title: "pointingElimination", fn: pointingElimination, score : 80 },
//harder for human to spot
{title: "hiddenPair", fn: hiddenPair, score : 90 },
{title: "nakedTriplet", fn: nakedTriplet, score : 100 },
//never gets used unless above strats are turned off?
{title: "hiddenTriplet", fn: hiddenTriplet, score : 140 },
//never gets used unless above strats are turned off?
{title: "nakedQuad", fn: nakedQuad, score : 150 },
//never gets used unless above strats are turned off?
{title: "hiddenQuad", fn: hiddenQuad, score : 280 }
],
//nr of times each strategy has been used for solving this board - used to calculate difficulty score
usedStrategies = [],
/*board variable gets enhanced into list of objects on init:
,{
val: null
,candidates: [
]
}
*/
board = [],
boardSize,
boardNumbers, // array of 1-9 by default, generated in initBoard
//indexes of cells in each house - generated on the fly based on boardSize
houses = [
//hor. rows
[],
//vert. rows
[],
//boxes
[]
];
/*
* selectors
*-----------*/
var $board = $(this),
$boardInputs, //created
$boardInputCandidates; //created
/*
* methods
*-----------*/
//shortcut for logging..
function log(msg){
if(window.console && console.log)
console.log(msg);
}
//array contains function
var contains = function(a, obj) {
for (var i = 0; i < a.length; i++) {
if (a[i] === obj) {
return true;
}
}
return false;
};
var uniqueArray = function(a) {
var temp = {};
for (var i = 0; i < a.length; i++)
temp[a[i]] = true;
var r = [];
for (var k in temp)
r.push(k);
return r;
};
/* calcBoardDifficulty
* --------------
* TYPE: solely based on strategies required to solve board (i.e. single count per strategy)
* SCORE: distinguish between boards of same difficulty.. based on point system. Needs work.
* -----------------------------------------------------------------*/
var calcBoardDifficulty = function(usedStrategies){
var boardDiff = {};
if(usedStrategies.length < 3)
boardDiff.level = DIFFICULTY_EASY;
else if(usedStrategies.length < 4)
boardDiff.level = DIFFICULTY_MEDIUM;
else
boardDiff.level = DIFFICULTY_HARD;
var totalScore = 0;
for(var i=0; i < strategies.length; i++){
var freq = usedStrategies[i];
if(!freq)
continue; //undefined or 0, won't effect score
var stratObj = strategies[i];
totalScore += freq * stratObj.score;
}
boardDiff.score = totalScore;
//log("totalScore: "+totalScore);
if(totalScore > 750)
// if(totalScore > 2200)
boardDiff.level = DIFFICULTY_VERY_HARD;
return boardDiff;
};
/* isBoardFinished
* -----------------------------------------------------------------*/
var isBoardFinished = function(){
for (var i=0; i < boardSize*boardSize; i++){
if(board[i].val === null)
return false;
}
return true;
};
/* generateHouseIndexList
* -----------------------------------------------------------------*/
var generateHouseIndexList = function(){
// reset houses
houses = [
//hor. rows
[],
//vert. rows
[],
//boxes
[]
]
var boxSideSize = Math.sqrt(boardSize);
for(var i=0; i < boardSize; i++){
var hrow = []; //horisontal row
var vrow = []; //vertical row
var box = [];
for(var j=0; j < boardSize; j++){
hrow.push(boardSize*i + j);
vrow.push(boardSize*j + i);
if(j < boxSideSize){
for(var k=0; k < boxSideSize; k++){
//0, 0,0, 27, 27,27, 54, 54, 54 for a standard sudoku
var a = Math.floor(i/boxSideSize) * boardSize * boxSideSize;
//[0-2] for a standard sudoku
var b = (i%boxSideSize) * boxSideSize;
var boxStartIndex = a +b; //0 3 6 27 30 33 54 57 60
//every boxSideSize box, skip boardSize num rows to next box (on new horizontal row)
//Math.floor(i/boxSideSize)*boardSize*2
//skip across horizontally to next box
//+ i*boxSideSize;
box.push(boxStartIndex + boardSize*j + k);
}
}
}
houses[0].push(hrow);
houses[1].push(vrow);
houses[2].push(box);
}
};
/* initBoard
* --------------
* inits board, variables.
* -----------------------------------------------------------------*/
var initBoard = function(opts){
var alreadyEnhanced = (board[0] !== null && typeof board[0] === "object");
var nullCandidateList = [];
boardNumbers = [];
boardSize = (!board.length && opts.boardSize) || Math.sqrt(board.length) || 9;
$board.attr("data-board-size", boardSize);
if(boardSize % 1 !== 0 || Math.sqrt(boardSize) % 1 !== 0) {
log("invalid boardSize: "+boardSize);
if(typeof opts.boardErrorFn === "function")
opts.boardErrorFn({msg: "invalid board size"});
return;
}
for (var i=0; i < boardSize; i++){
boardNumbers.push(i+1);
nullCandidateList.push(null);
}
generateHouseIndexList();
if(!alreadyEnhanced){
//enhance board to handle candidates, and possibly other params
for(var j=0; j < boardSize*boardSize ; j++){
var cellVal = (typeof board[j] === "undefined") ? null : board[j];
var candidates = cellVal === null ? boardNumbers.slice() : nullCandidateList.slice();
board[j] = {
val: cellVal,
candidates: candidates
//title: "" possibl add in 'A1. B1...etc
};
}
}
};
/* renderBoard
* --------------
* dynamically renders the board on the screen (into the DOM), based on board variable
* -----------------------------------------------------------------*/
var renderBoard = function(){
//log("renderBoard");
//log(board);
var htmlString = "";
for(var i=0; i < boardSize*boardSize; i++){
htmlString += renderBoardCell(board[i], i);
if((i+1) % boardSize === 0) {
htmlString += "<br>";
}
}
//log(htmlString);
$board.append(htmlString);
//save important board elements
$boardInputs = $board.find("input");
$boardInputCandidates = $board.find(".candidates");
};
/* renderBoardCell
* -----------------------------------------------------------------*/
var renderBoardCell = function(boardCell, id){
var val = (boardCell.val === null) ? "" : boardCell.val;
var candidates = boardCell.candidates || [];
var candidatesString = buildCandidatesString(candidates);
var maxlength = (boardSize < 10) ? " maxlength='1'" : "";
return "<div class='sudoku-board-cell'>" +
//want to use type=number, but then have to prevent chrome scrolling and up down key behaviors..
"<input type='text' pattern='\\d*' novalidate id='input-"+id+"' value='"+val+"'"+maxlength+">" +
"<div id='input-"+id+"-candidates' class='candidates'>" + candidatesString + "</div>" +
"</div>";
};
/* buildCandidatesString
* -----------------------------------------------------------------*/
var buildCandidatesString = function(candidatesList){
var s="";
for(var i=1; i<boardSize+1; i++){
if(contains(candidatesList,i))
s+= "<div>"+i+"</div> ";
else
s+= "<div> </div> ";
}
return s;
};
/* updateUI
* --------------
* updates the UI
* -----------------------------------------------------------------
var updateUI = function(opts){
var opts = opts || {};
var paintNew = (typeof opts.paintNew !== "undefined") ? opts.paintNew : true;
updateUIBoard(paintNew);
}*/
/* updateUIBoard -
* --------------
* updates the board with our latest values
* -----------------------------------------------------------------*/
var updateUIBoard = function(paintNew){
//log("re painting every input on board..");
$boardInputs
.removeClass("highlight-val")
.each(function(i,v){
var $input = $(this);
var newVal = board[i].val;
//if(newVal && parseInt($input.val()) !== newVal) {
$input.val(newVal);
if(paintNew)
$input.addClass("highlight-val");
//}
var $candidates = $input.siblings(".candidates");
$candidates.html(buildCandidatesString(board[i].candidates));
});
};
/* updateUIBoardCell -
* --------------
* updates ONE cell on the board with our latest values
* -----------------------------------------------------------------*/
var updateUIBoardCell = function(cellIndex, opts){
opts = opts || {};
//log("updateUIBoardCell: "+cellIndex);
//if(!(opts.mode && opts.mode === "only-candidates")){
var newVal = board[cellIndex].val;
//$boardInputs.removeClass("highlight-val");
//shouldn't always add hightlight-val class
$("#input-"+cellIndex)
.val(newVal)
.addClass("highlight-val");
//}
$("#input-"+cellIndex+"-candidates")
.html(buildCandidatesString(board[cellIndex].candidates));
};
/* uIBoardHighlightRemoveCandidate
* --------------
* highlight candidate in cell that is about to be removed
* -----------------------------------------------------------------*/
var uIBoardHighlightRemoveCandidate = function(cellIndex, digit){
$("#input-"+cellIndex+"-candidates div:nth-of-type("+digit+")").addClass("candidate--to-remove");
};
/* uIBoardHighlightCandidate -
* --------------
* highight candidate in cell that helps eliminate another candidate
* -----------------------------------------------------------------*/
var uIBoardHighlightCandidate = function(cellIndex, digit){
$("#input-"+cellIndex+"-candidates div:nth-of-type("+digit+")").addClass("candidate--highlight");
};
/* removeCandidatesFromCell
-----------------------------------------------------------------*/
var removeCandidatesFromCell = function(cell, candidates){
var boardCell = board[cell];
var c = boardCell.candidates;
var cellUpdated = false;
for(var i=0; i < candidates.length; i++){
//-1 because candidate '1' is at index 0 etc.
if(c[candidates[i]-1] !== null) {
c[candidates[i]-1] = null; //writes to board variable
cellUpdated = true;
}
}
if(cellUpdated && solveMode === SOLVE_MODE_STEP)
updateUIBoardCell(cell, {mode: "only-candidates"});
};
/* removeCandidatesFromCells
* ---returns list of cells where any candidats where removed
-----------------------------------------------------------------*/
var removeCandidatesFromCells = function(cells, candidates){
//log("removeCandidatesFromCells");
var cellsUpdated = [];
for (var i=0; i < cells.length; i++){
var c = board[cells[i]].candidates;
for(var j=0; j < candidates.length; j++){
var candidate = candidates[j];
//-1 because candidate '1' is at index 0 etc.
if(c[candidate-1] !== null) {
c[candidate-1] = null; //NOTE: also deletes them from board variable
cellsUpdated.push(cells[i]); //will push same cell multiple times
if(solveMode===SOLVE_MODE_STEP){
//highlight candidate as to be removed on board
uIBoardHighlightRemoveCandidate(cells[i],candidate);
}
}
}
}
return cellsUpdated;
};
var highLightCandidatesOnCells = function(candidates, cells){
for(var i=0; i < cells.length; i++){
var cellCandidates = board[cells[i]].candidates;
for(var j=0; j < cellCandidates.length; j++){
if(contains(candidates, cellCandidates[j]))
uIBoardHighlightCandidate(cells[i],cellCandidates[j]);
}
}
};
var resetBoardVariables = function() {
boardFinished = false;
boardError = false;
onlyUpdatedCandidates = false;
usedStrategies = [];
gradingMode = false;
};
/* clearBoard
-----------------------------------------------------------------*/
var clearBoard = function(){
resetBoardVariables();
//reset board variable
var cands = boardNumbers.slice(0);
for(var i=0; i <boardSize*boardSize;i++){
board[i] = {
val: null,
candidates: cands.slice()
};
}
//reset UI
$boardInputs
.removeClass("highlight-val")
.val("");
updateUIBoard(false);
};
var getNullCandidatesList = function() {
var l = [];
for (var i=0; i < boardSize; i++){
l.push(null);
}
return l;
};
/* resetCandidates
-----------------------------------------------------------------*/
var resetCandidates = function(updateUI){
var resetCandidatesList = boardNumbers.slice(0);
for(var i=0; i <boardSize*boardSize;i++){
if(board[i].val === null){
board[i].candidates = resetCandidatesList.slice(); //otherwise same list (not reference!) on every cell
if(updateUI !== false)
$("#input-"+i+"-candidates").html(buildCandidatesString(resetCandidatesList));
} else if(updateUI !== false) {
$("#input-"+i+"-candidates").html("");
}
}
};
/* setBoardCell - does not update UI
-----------------------------------------------------------------*/
var setBoardCell = function(cellIndex, val){
var boardCell = board[cellIndex];
//update val
boardCell.val = val;
if(val !== null)
boardCell.candidates = getNullCandidatesList();
};
/* indexInHouse
* --------------
* returns index (0-9) for digit in house, false if not in house
* NOTE: careful evaluating returned index is IN row, as 0==false.
* -----------------------------------------------------------------*/
var indexInHouse = function(digit,house){
for(var i=0; i < boardSize; i++){
if(board[house[i]].val===digit)
return i;
}
//not in house
return false;
};
/* housesWithCell
* --------------
* returns houses that a cell belongs to
* -----------------------------------------------------------------*/
var housesWithCell = function(cellIndex){
var boxSideSize = Math.sqrt(boardSize);
var houses = [];
//horisontal row
var hrow = Math.floor(cellIndex/boardSize);
houses.push(hrow);
//vertical row
var vrow = Math.floor(cellIndex%boardSize);
houses.push(vrow);
//box
var box = (Math.floor(hrow/boxSideSize)*boxSideSize) + Math.floor(vrow/boxSideSize);
houses.push(box);
return houses;
};
/* numbersLeft
* --------------
* returns unused numbers in a house
* -----------------------------------------------------------------*/
var numbersLeft = function(house){
var numbers = boardNumbers.slice();
for(var i=0; i < house.length; i++){
for(var j=0; j < numbers.length; j++){
//remove all numbers that are already being used
if(numbers[j] === board[house[i]].val)
numbers.splice(j,1);
}
}
//return remaining numbers
return numbers;
};
/* numbersTaken
* --------------
* returns used numbers in a house
* -----------------------------------------------------------------*/
var numbersTaken = function(house){
var numbers = [];
for(var i=0; i < house.length; i++){
var n = board[house[i]].val;
if(n !== null)
numbers.push(n);
}
//return remaining numbers
return numbers;
};
/* candidatesLeft
* --------------
* returns list of candidates for cell (with null's removed)
* -----------------------------------------------------------------*/
var candidatesLeft = function(cellIndex){
var t = [];
var candidates = board[cellIndex].candidates;
for (var i=0; i < candidates.length; i++){
if (candidates[i] !== null)
t.push(candidates[i]);
}
return t;
};
/* cellsForCandidate
* --------------
* returns list of possible cells (cellIndex) for candidate (in a house)
* -----------------------------------------------------------------*/
var cellsForCandidate = function(candidate,house){
var t = [];
for(var i=0; i < house.length; i++){
var cell = board[house[i]];
var candidates = cell.candidates;
if(contains(candidates, candidate))
t.push(house[i]);
}
return t;
};
/* openSingles
* --------------
* checks for houses with just one empty cell - fills it in board variable if so
* -- returns effectedCells - the updated cell(s), or false
* -----------------------------------------------------------------*/
function openSingles(){
//log("looking for openSingles");
//for each type of house..(hor row / vert row / box)
var hlength = houses.length;
for(var i=0; i < hlength; i++){
//for each such house
var housesCompleted = 0; //if goes up to 9, sudoku is finished
for(var j=0; j < boardSize; j++){
var emptyCells = [];
// for each cell..
for (var k=0; k < boardSize; k++){
var boardIndex = houses[i][j][k];
if(board[boardIndex].val === null) {
emptyCells.push({house: houses[i][j], cell: boardIndex});
if(emptyCells.length > 1) {
//log("more than one empty cell, house area :["+i+"]["+j+"]");
break;
}
}
}
//one empty cell found
if(emptyCells.length === 1){
var emptyCell = emptyCells[0];
//grab number to fill in in cell
var val = numbersLeft(emptyCell.house);
if(val.length > 1) {
//log("openSingles found more than one answer for: "+emptyCell.cell+" .. board incorrect!");
boardError = true; //to force solve all loop to stop
return -1; //error
}
//log("fill in single empty cell " + emptyCell.cell+", val: "+val);
setBoardCell(emptyCell.cell, val[0]); //does not update UI
if(solveMode===SOLVE_MODE_STEP)
uIBoardHighlightCandidate(emptyCell.cell, val[0]);
return [emptyCell.cell];
}
//no empty ells..
if(emptyCells.length === 0) {
housesCompleted++;
//log(i+" "+j+": "+housesCompleted);
if(housesCompleted === boardSize){
boardFinished = true;
return -1; //special case, done
}
}
}
}
return false;
}
/* visualEliminationOfCandidates
* --------------
* ALWAYS returns false
* -- special compared to other strats: doesn't step - updates whole board,
in one go. Since it also only updates candidates, we can skip straight to next strat, since we know that neither this one nor the one(s) before (that only look at actual numbers on board), will find anything new.
* -----------------------------------------------------------------*/
function visualEliminationOfCandidates(){
//for each type of house..(hor row / vert row / box)
var hlength = houses.length;
for(var i=0; i < hlength; i++){
//for each such house
for(var j=0; j < boardSize; j++){
var house = houses[i][j];
var candidatesToRemove = numbersTaken(house);
//log(candidatesToRemove);
// for each cell..
for (var k=0; k < boardSize; k++){
var cell = house[k];
var candidates = board[cell].candidates;
removeCandidatesFromCell(cell, candidatesToRemove);
}
}
}
return false;
}
/* visualElimination
* --------------
* Looks for houses where a digit only appears in one slot
* -meaning we know the digit goes in that slot.
* -- returns effectedCells - the updated cell(s), or false
* -----------------------------------------------------------------*/
function visualElimination(){
//log("visualElimination");
//for each type of house..(hor row / vert row / box)
var hlength = houses.length;
for(var i=0; i < hlength; i++){
//for each such house
for(var j=0; j < boardSize; j++){
var house = houses[i][j];
var digits = numbersLeft(house);
//for each digit left for that house
for (var k=0; k < digits.length; k++){
var digit = digits[k];
var possibleCells = [];
//for each cell in house
for(var l=0; l < boardSize; l++){
var cell = house[l];
var boardCell = board[cell];
//if the digit only appears as a candidate in one slot, that's where it has to go
if (contains(boardCell.candidates, digit)){
possibleCells.push(cell);
if(possibleCells.length > 1)
break; //no we can't tell anything in this case
}
}
if(possibleCells.length === 1){
var cellIndex = possibleCells[0];
//log("only slot where "+digit+" appears in house. ");
setBoardCell(cellIndex, digit); //does not update UI
if(solveMode===SOLVE_MODE_STEP)
uIBoardHighlightCandidate(cellIndex, digit);
onlyUpdatedCandidates = false;
return [cellIndex]; //one step at the time
}
}
}
}
return false;
}
/* singleCandidate
* --------------
* Looks for cells with only one candidate
* -- returns effectedCells - the updated cell(s), or false
* -----------------------------------------------------------------*/
function singleCandidate(){
//before we start with candidate strategies, we need to update candidates from last round:
visualEliminationOfCandidates(); //TODO: a bit hackyy, should probably not be here
//for each cell
for(var i=0; i < board.length; i++){
var cell = board[i];
var candidates = cell.candidates;
//for each candidate for that cell
var possibleCandidates = [];
for (var j=0; j < candidates.length; j++){
if (candidates[j] !== null)
possibleCandidates.push(candidates[j]);
if(possibleCandidates.length >1)
break; //can't find answer here
}
if(possibleCandidates.length === 1){
var digit = possibleCandidates[0];
//log("only one candidate in cell: "+digit+" in house. ");
setBoardCell(i, digit); //does not update UI
if(solveMode===SOLVE_MODE_STEP)
uIBoardHighlightCandidate(i, digit);
onlyUpdatedCandidates = false;
return [i]; //one step at the time
}
}
return false;
}
/* pointingElimination
* --------------
* if candidates of a type (digit) in a box only appar on one row, all other
* same type candidates can be removed from that row
------------OR--------------
* same as above, but row instead of box, and vice versa.
* -- returns effectedCells - the updated cell(s), or false
* -----------------------------------------------------------------*/
function pointingElimination(){
var effectedCells = false;
//for each type of house..(hor row / vert row / box)
var hlength = houses.length;
for(var a=0; a < hlength; a++){
var houseType = a;
for(var i=0; i < boardSize; i++){
var house = houses[houseType][i];
//for each digit left for this house
var digits = numbersLeft(house);
for(var j=0; j< digits.length; j++){
var digit = digits[j];
//check if digit (candidate) only appears in one row (if checking boxes),
//, or only in one box (if checking rows)
var sameAltHouse = true; //row if checking box, and vice versa
var houseId = -1;
//when point checking from box, need to compare both kind of rows
//that box cells are also part of, so use houseTwoId as well
var houseTwoId = -1;
var sameAltTwoHouse = true;
var cellsWithCandidate = [];
//var cellDistance = null;
//for each cell
for(var k=0; k < house.length; k++){
var cell = house[k];
if (contains(board[cell].candidates,digit)) {
var cellHouses = housesWithCell(cell);
var newHouseId = (houseType ===2) ? cellHouses[0] : cellHouses[2];
var newHouseTwoId = (houseType ===2) ? cellHouses[1] : cellHouses[2];
//if(cellsWithCandidate.length > 0){ //why thice the same?
if(cellsWithCandidate.length > 0){
if(newHouseId !== houseId){
sameAltHouse = false;
}
if(houseTwoId !== newHouseTwoId){
sameAltTwoHouse = false;
}
if(sameAltHouse === false && sameAltTwoHouse === false){
break; //not in same altHouse (box/row)
}
}
//}
houseId = newHouseId;
houseTwoId = newHouseTwoId;
cellsWithCandidate.push(cell);
}
}
if((sameAltHouse === true || sameAltTwoHouse === true ) && cellsWithCandidate.length > 0){
//log("sameAltHouse..");
//we still need to check that this actually eliminates something, i.e. these possible cells can't be only in house
//first figure out what kind of house we are talking about..
var h = housesWithCell(cellsWithCandidate[0]);
var altHouseType = 2;
if(houseType ===2){
if(sameAltHouse)
altHouseType = 0;
else
altHouseType = 1;
}
var altHouse = houses[altHouseType][h[altHouseType]];
var cellsEffected = [];
//log("houses["+houseType+"]["+h[houseType]+"].length: "+houses[houseType][h[houseType]].length);
//need to remove cellsWithCandidate - from cells to remove from
for (var x=0; x< altHouse.length; x++){
if(!contains(cellsWithCandidate, altHouse[x])) {
cellsEffected.push(altHouse[x]);
}
}
//log("houses["+houseType+"]["+h[houseType]+"].length: "+houses[houseType][h[houseType]].length);
//remove all candidates on altHouse, outside of house
var cellsUpdated = removeCandidatesFromCells(cellsEffected, [digit]);
if(cellsUpdated.length > 0){
// log("pointing: digit "+digit+", from houseType: "+houseType);
if(solveMode === SOLVE_MODE_STEP)
highLightCandidatesOnCells([digit], cellsWithCandidate);
onlyUpdatedCandidates = true;
//return cellsUpdated.concat(cellsWithCandidate);
//only return cells where we actually update candidates
return cellsUpdated;
}
}
}
}
}
return false;
}
/* nakedCandidates
* --------------
* looks for n nr of cells in house, which together has exactly n unique candidates.
this means these candidates will go into these cells, and can be removed elsewhere in house.
*
* -- returns effectedCells - the updated cell(s), or false
* -----------------------------------------------------------------*/
function nakedCandidates(n){
//for each type of house..(hor row / vert row / box)
var hlength = houses.length;
for(var i=0; i < hlength; i++){
//for each such house
for(var j=0; j < boardSize; j++){
//log("["+i+"]"+"["+j+"]");
var house = houses[i][j];
if(numbersLeft(house).length <= n) //can't eliminate any candidates
continue;
var combineInfo = []; //{cell: x, candidates: []}, {} ..
//combinedCandidates,cellsWithCandidate;
var minIndexes = [-1];
//log("--------------");
//log("house: ["+i+"]["+j+"]");
//checks every combo of n candidates in house, returns pattern, or false
var result = checkCombinedCandidates(house, 0);
if(result !== false)
return result;
}
}
return false; //pattern not found
function checkCombinedCandidates(house, startIndex){
//log("startIndex: "+startIndex);
for(var i=Math.max(startIndex, minIndexes[startIndex]); i < boardSize-n+startIndex; i++){
//log(i);
//never check this cell again, in this loop
minIndexes[startIndex] = i+1;
//or in a this loop deeper down in recursions
minIndexes[startIndex+1] = i+1;
//if(startIndex === 0){
// combinedCandidates = [];
// cellsWithCandidate = []; //reset
//}
var cell = house[i];
var cellCandidates = candidatesLeft(cell);
if(cellCandidates.length === 0 || cellCandidates.length > n)
continue;
//try adding this cell and it's cellCandidates,
//but first need to check that that doesn't make (unique) amount of
//candidates in combineInfo > n
//if this is the first item we add, we don't need this check (above one is enough)
if(combineInfo.length > 0){
var temp = cellCandidates.slice();
for(var a =0; a < combineInfo.length; a++){
var candidates = combineInfo[a].candidates;
for(var b=0; b < candidates.length; b++){
if(!contains(temp,candidates[b]))
temp.push(candidates[b]);
}
}
if(temp.length > n){
continue; //combined candidates spread over > n cells, won't work
}