/
SudokuStore.java
1765 lines (1760 loc) · 66.6 KB
/
SudokuStore.java
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
/*
* @(#)SudokuStore.java 1.1.1 2016-04-18
*
* You may use this software under the condition of "Simplified BSD License"
*
* Copyright 2016 MARIUSZ GROMADA. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY MARIUSZ GROMADA ``AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL <COPYRIGHT HOLDER> OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and should not be interpreted as representing official policies, either expressed
* or implied, of MARIUSZ GROMADA.
*
* If you have any questions/bugs feel free to contact:
*
* Mariusz Gromada
* mariuszgromada.org@gmail.com
* http://janetsudoku.mariuszgromada.org
* http://mathparser.org
* http://mathspace.pl
* http://github.com/mariuszgromada/Janet-Sudoku
* http://janetsudoku.codeplex.com
* http://sourceforge.net/projects/janetsudoku
* http://bitbucket.org/mariuszgromada/janet-sudoku
* http://github.com/mariuszgromada/MathParser.org-mXparser
*
*
* Asked if he believes in one God, a mathematician answered:
* "Yes, up to isomorphism."
*/
package org.mariuszgromada.math.janetsudoku;
import java.util.ArrayList;
import org.mariuszgromada.math.janetsudoku.utils.ArrayX;
import org.mariuszgromada.math.janetsudoku.utils.DateTimeX;
import org.mariuszgromada.math.janetsudoku.utils.FileX;
/**
* Storehouse for various things used in library, i.e. sudoku board examples.
*
* @author <b>Mariusz Gromada</b><br>
* <a href="mailto:mariuszgromada.org@gmail.com">mariuszgromada.org@gmail.com</a><br>
* <a href="http://janetsudoku.mariuszgromada.org" target="_blank">Janet Sudoku - project web page</a><br>
* <a href="http://mathspace.pl" target="_blank">MathSpace.pl</a><br>
* <a href="http://mathparser.org" target="_blank">MathParser.org - mXparser project page</a><br>
* <a href="http://github.com/mariuszgromada/Janet-Sudoku" target="_blank">Janet Sudoku on GitHub</a><br>
* <a href="http://janetsudoku.codeplex.com" target="_blank">Janet Sudoku on CodePlex</a><br>
* <a href="http://sourceforge.net/projects/janetsudoku" target="_blank">Janet Sudoku on SourceForge</a><br>
* <a href="http://bitbucket.org/mariuszgromada/janet-sudoku" target="_blank">Janet Sudoku on BitBucket</a><br>
* <a href="http://github.com/mariuszgromada/MathParser.org-mXparser" target="_blank">mXparser-MathParser.org on GitHub</a><br>
*
* @version 1.1.1
*/
public final class SudokuStore {
/**
* Sudoku solver version.
*/
public static final String JANET_SUDOKU_VERSION = "1.1.1";
/**
* Sudoku solver name.
*/
public static final String JANET_SUDOKU_NAME = "Janet-Sudoku";
/**
* Number of Sudoku puzzles examples.
*
* @see SudokuPuzzles
* @see SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES
*/
public static final int NUMBER_OF_PUZZLE_EXAMPLES = SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES;
/**
* Board size derived form SudokuBoard class.
*/
private static final int BOARD_SIZE = SudokuBoard.BOARD_SIZE;
/**
* Sudoku board sub-square size derived from SudokuBoard class.
*/
private static final int BOARD_SUB_SQURE_SIZE = SudokuBoard.BOARD_SUB_SQURE_SIZE;
/**
* Number of 9x3 column segments or 3x9 row segments.
* derived from SudokuBoard class.
*/
private static final int BOARD_SEGMENTS_NUMBER = SudokuBoard.BOARD_SEGMENTS_NUMBER;
/**
* Number of available random board transformations.
*
* @see SudokuStore#randomBoardTransf(int[][])
* @see SudokuStore#seqOfRandomBoardTransf(int[][])
* @see SudokuStore#seqOfRandomBoardTransf(int[][], int)
*/
public static final int AVAILABLE_RND_BOARD_TRANSF = 17;
/**
* Default sequence length of random board transformations.
*
* @see SudokuStore#randomBoardTransf(int[][])
* @see SudokuStore#seqOfRandomBoardTransf(int[][])
* @see SudokuStore#seqOfRandomBoardTransf(int[][], int)
*/
public static final int DEFAULT_RND_TRANSF_SEQ_LENGTH = 1000;
/**
* System specific new line separator
*/
public static final String NEW_LINE_SEPARATOR = System.getProperty("line.separator");
/**
* Threads number.
*/
public static final int THREADS_NUMBER = Runtime.getRuntime().availableProcessors();
/**
* Default number of iterations while calculating
* puzzle rating.
*/
private static final int RATING_DEF_NUM_OF_ITERATIONS = 1000;
/*
* ======================================================
* Loading / getting board methods
* ======================================================
*/
/**
* Gets Sudoku example for the Sudoku Store.
* @param exampleNumber Example number.
* @return Sudoku example is exists, otherwise null.
* @see SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES
* @see SudokuPuzzles#getPuzzleExample(int)
*/
public static final int[][] getPuzzleExample(int exampleNumber) {
return SudokuPuzzles.getPuzzleExample(exampleNumber);
}
/**
* Gets Sudoku example for the Sudoku Store.
* @return Sudoku example is exists, otherwise null.
* @see SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES
* @see SudokuPuzzles#getPuzzleExample(int)
*/
public static final int[][] getPuzzleExample() {
return SudokuPuzzles.getPuzzleExample( SudokuStore.randomIndex(SudokuPuzzles.NUMBER_OF_PUZZLE_EXAMPLES) );
}
/**
* Returns pre-calculated puzzle example difficulty rating based on
* the average number of steps-back performed while recursive
* solving sudoku board.
*
* @param exampleNumber The example number {@link SudokuPuzzles#NUMBER_OF_PUZZLE_EXAMPLES}
* @return Puzzle example difficulty rating if example exists, otherwise -1.
*/
public static final double getPuzzleExampleRating(int exampleNumber) {
return SudokuPuzzles.getPuzzleExampleRating(exampleNumber);
}
/**
* Calculates difficulty of Sudoku puzzle. Returned difficulty level is an average
* of number of closed routes while performing recursive steps in order to find solution.
* This is multi-threading procedure.
*
* @param sudokuPuzzle Sudoku puzzle to be rated.
* @return If puzzle does not contain an error then difficulty rating is returned.
* If puzzle contains obvious error then {@link ErrorCodes#SUDOKUSTORE_CALCULATEPUZZLERATING_PUZZLE_ERROR}.
* If puzzle has no solutions then {@link ErrorCodes#SUDOKUSTORE_CALCULATEPUZZLERATING_NO_SOLUTION}.
* If solution is non-unique then {@link ErrorCodes#SUDOKUSTORE_CALCULATEPUZZLERATING_NON_UNIQUE_SOLUTION}.
*/
public static final int calculatePuzzleRating(final int[][] sudokuPuzzle) {
if (checkPuzzle(sudokuPuzzle) == false)
return ErrorCodes.SUDOKUSTORE_CALCULATEPUZZLERATING_PUZZLE_ERROR;
SudokuSolver s = new SudokuSolver(sudokuPuzzle);
int solType = s.checkIfUniqueSolution();
if (solType == SudokuSolver.SOLUTION_NOT_EXISTS)
return ErrorCodes.SUDOKUSTORE_CALCULATEPUZZLERATING_NO_SOLUTION;
if (solType == SudokuSolver.SOLUTION_NON_UNIQUE)
return ErrorCodes.SUDOKUSTORE_CALCULATEPUZZLERATING_NON_UNIQUE_SOLUTION;
/*
* Multi-threading implementation
*/
int threadIterNum = RATING_DEF_NUM_OF_ITERATIONS / THREADS_NUMBER;
final int[][] results = new int[THREADS_NUMBER][threadIterNum];
/**
* Runner implementation.
*/
class Runner implements Runnable {
/**
* Thread id.
*/
int threadId;
/**
* Number of iterations.
*/
int iterNum;
/**
* Default constructor.
* @param threadId Thread id.
* @param assigments Test assigned to that thread.
*/
Runner(int threadId, int iterNum) {
this.threadId = threadId;
this.iterNum = iterNum;
}
/**
* Synchronized method to store test results.
* @param t Test id.
* @param result TEst result.
*/
private void setTestResult(int i, int result) {
synchronized(results) {
results[threadId][i] = result;
}
}
public void run() {
for (int i = 0; i < iterNum; i++) {
SudokuSolver s = new SudokuSolver(sudokuPuzzle);
s.solve();
setTestResult(i, s.getClosedRoutesNumber());
}
}
}
Runner[] runners = new Runner[THREADS_NUMBER];
Thread[] threads = new Thread[THREADS_NUMBER];
for (int t = 0; t < THREADS_NUMBER; t++) {
runners[t] = new Runner(t, threadIterNum);
threads[t] = new Thread(runners[t]);
}
for (int t = 0; t < THREADS_NUMBER; t++) {
threads[t].start();
}
for (int t = 0; t < THREADS_NUMBER; t++) {
try {
threads[t].join();
} catch (InterruptedException e) {
e.printStackTrace();
return ErrorCodes.SUDOKUSTORE_CALCULATEPUZZLERATING_THREADS_JOIN_FAILED;
}
}
int sum = 0;
for (int t = 0; t < THREADS_NUMBER; t++)
for (int i = 0; i < threadIterNum; i++)
sum+=results[t][i];
return sum / (THREADS_NUMBER * threadIterNum);
}
/**
* Loads Sudoku board from text file.
*
* Format:
* Any character different than '1-9' and '.' is being removed.
* Any line starting with '#' is being removed.
* Any empty line is being removed.
* Any final line having less than 9 characters is being removed.
*
* If number of final lines is less then 9 then null is returned.
*
* Finally 9 starting characters for first 9 lines is the
* loaded board definition.
*
* @param filePath Path to the file with Sudoku board definition.
* @return Array representing loaded Sudoku board,
* null - if problem occurred while loading.
*/
public static final int[][] loadBoard(String filePath) {
ArrayList<String> fileLines = FileX.readFileLines2ArraList(filePath);
return loadBoard(fileLines);
}
/**
* Loads Sudoku board from list of strings (each string as a
* one row)
*
* Format:
* Any character different than '1-9' and '.' is being removed.
* Any line starting with '#' is being removed.
* Any empty line is being removed.
* Any final line having less than 9 characters is being removed.
*
* If number of final lines is less then 9 then null is returned.
*
* Finally 9 starting characters for first 9 lines is the
* loaded board definition.
*
* @param boardDefinition Board definition (list of strings).
* @return Array representing loaded Sudoku board,
* null - if problem occurred while loading.
*/
public static final int[][] loadBoard(ArrayList<String> boardDefinition) {
return loadBoard( ArrayX.toArray(String.class, boardDefinition) );
}
/**
* Loads Sudoku board from array of strings (each string as a
* one row)
*
* Format:
* Any character different than '1-9' and '.' is being removed.
* Any line starting with '#' is being removed.
* Any empty line is being removed.
* Any final line having less than 9 characters is being removed.
*
* If number of final lines is less then 9 then null is returned.
*
* Finally 9 starting characters for first 9 lines is the
* loaded board definition.
*
* @param boardDefinition Board definition (array of strings).
* @return Array representing loaded Sudoku board,
* null - if problem occurred while loading.
*/
public static final int[][] loadBoard(String[] boardDefinition) {
ArrayList<String> sudokuRows = new ArrayList<String>();
if (boardDefinition == null) return null;
if (boardDefinition.length < BOARD_SIZE) return null;
for (String line : boardDefinition) {
if (line.length() > 0) {
if (line.charAt(0) != '#') {
String sudokuRow = "";
for (int j = 0; j < line.length(); j++) {
char c = line.charAt(j);
if (
(c == '1') ||
(c == '2') ||
(c == '3') ||
(c == '4') ||
(c == '5') ||
(c == '6') ||
(c == '7') ||
(c == '8') ||
(c == '9') ||
(c == '0') ||
(c == '.')
) sudokuRow = sudokuRow + c;
}
if (sudokuRow.length() >= BOARD_SIZE)
sudokuRows.add(sudokuRow.substring(0, BOARD_SIZE));
}
}
}
if (sudokuRows.size() < BOARD_SIZE) return null;
int[][] sudokuBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
String sudokuRow = sudokuRows.get(i);
for (int j = 0; j < BOARD_SIZE; j++) {
char c = sudokuRow.charAt(j);
int d = BoardCell.EMPTY;
if (c == '1') d = 1;
else if (c == '2') d = 2;
else if (c == '3') d = 3;
else if (c == '4') d = 4;
else if (c == '5') d = 5;
else if (c == '6') d = 6;
else if (c == '7') d = 7;
else if (c == '8') d = 8;
else if (c == '9') d = 9;
sudokuBoard[i][j] = d;
}
}
return sudokuBoard;
}
/**
* Loads Sudoku board from one string line ('0' and' '.' treated as empty cell).
* Any other char than '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', '.'
* is being filtered out.
*
* @param boardDefinition Board definition in one string line containing
* row after row.
* @return Loaded board if data is sufficient to fill 81 cells
* (including empty cells), otherwise null.
*/
public static final int[][] loadBoardFromStringLine(String boardDefinition) {
final int lastInex = BOARD_SIZE - 1;
if (boardDefinition == null) return null;
if (boardDefinition.length() < SudokuBoard.BOARD_CELLS_NUMBER) return null;
int [][] board = boardCopy(SudokuPuzzles.PUZZLE_EMPTY);
int cellNum = 0;
int i = 0;
int j = -1;
char[] line = boardDefinition.toCharArray();
for (int k = 0; k < line.length; k++) {
char c = line[k];
int d = -1;
if (c == '1') d = 1;
else if (c == '2') d = 2;
else if (c == '3') d = 3;
else if (c == '4') d = 4;
else if (c == '5') d = 5;
else if (c == '6') d = 6;
else if (c == '7') d = 7;
else if (c == '8') d = 8;
else if (c == '9') d = 9;
else if (c == '0') d = 0;
else if (c == '.') d = 0;
if ( (d >= 0) && (cellNum < SudokuBoard.BOARD_CELLS_NUMBER) ) {
j++;
cellNum++;
board[i][j] = d;
if ( j == lastInex) {
i++;
j = -1;
}
}
}
if (cellNum == SudokuBoard.BOARD_CELLS_NUMBER) return board;
else return null;
}
/**
* Loads Sudoku board from variadic list of strings (each string as a
* one row)
*
* Format:
* Any character different than '1-9' and '.' is being removed.
* Any line starting with '#' is being removed.
* Any empty line is being removed.
* Any final line having less than 9 characters is being removed.
*
* If number of final lines is less then 9 then null is returned.
*
* Finally 9 starting characters for first 9 lines is the
* loaded board definition.
*
* @param boardDefinition Board definition (variadic list of strings).
* @return Array representing loaded Sudoku board,
* null - if problem occurred while loading.
*/
public static final int[][] loadBoardFromStrings(String... boardDefinition) {
return loadBoard(boardDefinition);
}
/**
* Saves board to the text file.
*
* @param sudokuBoard Sudoku board to be saved.
* @param filePath Path to the file.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#boardToString(int[][])
*/
public static final boolean saveBoard(int[][] sudokuBoard, String filePath) {
String boardString = SudokuStore.boardToString(sudokuBoard);
return FileX.writeFile(filePath, boardString);
}
/**
* Saves board to the text file.
*
* @param sudokuBoard Sudoku board to be saved.
* @param filePath Path to the file.
* @param headComment Comment to be added at the head.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#boardToString(int[][], String)
*/
public static final boolean saveBoard(int[][] sudokuBoard, String filePath, String headComment) {
String boardString = SudokuStore.boardToString(sudokuBoard, headComment);
return FileX.writeFile(filePath, boardString);
}
/**
* Saves board to the text file.
*
* @param sudokuBoard Sudoku board to be saved.
* @param filePath Path to the file.
* @param headComment Comment to be added at the head.
* @param tailComment Comment to be added at the tail.
* @return True if saving was successful, otherwise false.
*
* @see SudokuStore#boardToString(int[][], String, String)
*/
public static final boolean saveBoard(int[][] sudokuBoard, String filePath, String headComment, String tailComment) {
String boardString = SudokuStore.boardToString(sudokuBoard, headComment, tailComment);
return FileX.writeFile(filePath, boardString);
}
/**
* Set all digits to zero.
*
* @param digits
* @see SudokuStore#checkSolvedBoard(int[][])
*/
private static final void clearDigits(int[] digits) {
for (int i = 1; i < 10; i++)
digits[i] = 0;
}
/**
* Returns found unique digits number.
*
* @param digits
* @see SudokuStore#checkSolvedBoard(int[][])
*
* @return Unique digits number.
*/
private static final int sumDigits(int[] digits) {
int s = 0;
for (int i = 1; i < 10; i++)
s += digits[i];
return s;
}
/**
* Returns maximum count of found digits
*
* @param digits
* @see SudokuStore#checkPuzzle(int[][])
*
* @return Unique digits number.
*/
private static final int maxDigitCount(int[] digits) {
int max = 0;
for (int i = 1; i < 10; i++)
if ( digits[i] > max) max = digits[i];
return max;
}
/**
* Checks whether solved board is correct.
*
* @param solvedBoard The solved board to be verified.
*
* @return True if solved board is correct, otherwise false.
*/
public static boolean checkSolvedBoard(int[][] solvedBoard) {
if (solvedBoard == null) return false;
if (solvedBoard.length != BOARD_SIZE) return false;
if (solvedBoard[0].length != BOARD_SIZE) return false;
int[] digits = new int[10];
for (int i = 0; i < BOARD_SIZE; i++) {
clearDigits(digits);
for (int j = 0; j < BOARD_SIZE; j++) {
int d = solvedBoard[i][j];
if ( (d < 1) || (d > 9) ) return false;
digits[d] = 1;
}
if (sumDigits(digits) != 9) return false;
}
for (int j = 0; j < BOARD_SIZE; j++) {
clearDigits(digits);
for (int i = 0; i < BOARD_SIZE; i++) {
int d = solvedBoard[i][j];
digits[d] = 1;
}
if (sumDigits(digits) != 9) return false;
}
for (int rowSeg = 0; rowSeg < BOARD_SEGMENTS_NUMBER; rowSeg++) {
int iSeg = boardSegmentStartIndex(rowSeg);
for (int colSeg = 0; colSeg < BOARD_SEGMENTS_NUMBER; colSeg++) {
int jSeg = boardSegmentStartIndex(colSeg);
clearDigits(digits);
for (int i = 0; i < BOARD_SUB_SQURE_SIZE; i++)
for (int j = 0; j < BOARD_SUB_SQURE_SIZE; j++) {
int d = solvedBoard[iSeg + i][jSeg + j];
digits[d] = 1;
}
if (sumDigits(digits) != 9) return false;
}
}
return true;
}
/**
* Checks whether Sudoku puzzle contains an obvious error.
*
* @param sudokuBoard The board to be verified.
*
* @return True if no obvious error, otherwise false.
*/
public static boolean checkPuzzle(int[][] sudokuBoard) {
if (sudokuBoard == null) return false;
if (sudokuBoard.length != BOARD_SIZE) return false;
if (sudokuBoard[0].length != BOARD_SIZE) return false;
int[] digits = new int[10];
for (int i = 0; i < BOARD_SIZE; i++) {
clearDigits(digits);
for (int j = 0; j < BOARD_SIZE; j++) {
int d = sudokuBoard[i][j];
if ( (d < 0) || (d > 9) ) return false;
digits[d]++;
}
if (maxDigitCount(digits) > 1) return false;
}
for (int j = 0; j < BOARD_SIZE; j++) {
clearDigits(digits);
for (int i = 0; i < BOARD_SIZE; i++) {
int d = sudokuBoard[i][j];
digits[d]++;
}
if (maxDigitCount(digits) > 1) return false;
}
for (int rowSeg = 0; rowSeg < BOARD_SEGMENTS_NUMBER; rowSeg++) {
int iSeg = boardSegmentStartIndex(rowSeg);
for (int colSeg = 0; colSeg < BOARD_SEGMENTS_NUMBER; colSeg++) {
int jSeg = boardSegmentStartIndex(colSeg);
clearDigits(digits);
for (int i = 0; i < BOARD_SUB_SQURE_SIZE; i++)
for (int j = 0; j < BOARD_SUB_SQURE_SIZE; j++) {
int d = sudokuBoard[iSeg + i][jSeg + j];
digits[d]++;
}
if (maxDigitCount(digits) > 1) return false;
}
}
return true;
}
/*
* ======================================================
* Allowed operation on Sudoku board
* ======================================================
*/
/*
* ======================================================
* Rotation methods
* ======================================================
*/
/**
* Clockwise rotation of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Clockwise rotated sudoku board.
*/
public static final int[][] rotateClockWise(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] rotatedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i< BOARD_SIZE; i++) {
int newColIndex = BOARD_SIZE - i - 1;
for (int j = 0; j < BOARD_SIZE; j++)
rotatedBoard[j][newColIndex] = sudokuBoard[i][j];
}
return rotatedBoard;
}
/**
* Counterclockwise rotation of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Clockwise rotated Sudoku board.
*/
public static final int[][] rotateCounterclockWise(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] rotatedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int j = 0; j < BOARD_SIZE; j++) {
int newRowIndex = BOARD_SIZE - j - 1;
for (int i = 0; i < BOARD_SIZE; i++)
rotatedBoard[newRowIndex][i] = sudokuBoard[i][j];
}
return rotatedBoard;
}
/*
* ======================================================
* Reflection methods
* ======================================================
*/
/**
* Horizontal reflection of the Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Horizontally reflected Sudoku board.
*/
public static final int[][] reflectHorizontally(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] reflectedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
int newRowIndex = BOARD_SIZE - i - 1;
for (int j = 0; j < BOARD_SIZE; j++) {
reflectedBoard[newRowIndex][j] = sudokuBoard[i][j];
}
}
return reflectedBoard;
}
/**
* Vertical reflection of the Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Vertically reflected Sudoku board.
*/
public static final int[][] reflectVertically(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] reflectedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int j = 0; j < BOARD_SIZE; j++) {
int newColIndex = BOARD_SIZE - j - 1;
for (int i = 0; i < BOARD_SIZE; i++) {
reflectedBoard[i][newColIndex] = sudokuBoard[i][j];
}
}
return reflectedBoard;
}
/**
* Diagonal (Top-Left -> Bottom-Right) reflection of the Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Diagonally (Top-Left -> Bottom-Right) reflection of the Sudoku board. reflected Sudoku board.
*/
public static final int[][] transposeTlBr(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] reflectedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
for (int j = 0; j < BOARD_SIZE; j++)
reflectedBoard[j][i] = sudokuBoard[i][j];
return reflectedBoard;
}
/**
* Diagonal (Top-Right -> Bottom-Left) reflection of the Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return Diagonally Top-Right -> Bottom-Left) reflection of the Sudoku board. reflected Sudoku board.
*/
public static final int[][] transposeTrBl(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int[][] reflectedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++) {
int newColIndex = BOARD_SIZE - i -1;
for (int j = 0; j < BOARD_SIZE; j++) {
int newRowIndex = BOARD_SIZE - j - 1;
reflectedBoard[newRowIndex][newColIndex] = sudokuBoard[i][j];
}
}
return reflectedBoard;
}
/*
* ======================================================
* Swapping methods
* ======================================================
*/
/**
* Swapping 2 row segments (3x9 each one) of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @param rowSeg1 First row segment id: 0, 1, 2.
* @param rowSeg2 Second row segment id: 0, 1, 2.
* @return New array containing values resulted form swapping
* row segments procedure. If both segments are equal
* or one of the segments id is not 0, 1, or 2, then exact
* copy of original board is returned.
*/
public static final int[][] swapRowSegments(int[][] sudokuBoard, int rowSeg1, int rowSeg2) {
if (sudokuBoard == null) return null;
int[][] newBoard = boardCopy(sudokuBoard);
if (rowSeg1 == rowSeg2) return newBoard;
if ( (rowSeg1 < 0) || (rowSeg1 > 2) ) return newBoard;
if ( (rowSeg2 < 0) || (rowSeg2 > 2) ) return newBoard;
int startRowSeg1 = boardSegmentStartIndex(rowSeg1);
int startRowSeg2 = boardSegmentStartIndex(rowSeg2);
for (int i = 0; i < BOARD_SUB_SQURE_SIZE; i++)
for (int j = 0; j < BOARD_SIZE; j++) {
newBoard[startRowSeg1 + i][j] = sudokuBoard[startRowSeg2 + i][j];
newBoard[startRowSeg2 + i][j] = sudokuBoard[startRowSeg1 + i][j];
}
return newBoard;
}
/**
* Swapping randomly selected 2 row segments (3x9 each one) of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array containing values resulted form swapping
* column segments procedure.
*/
public static final int[][] swapRowSegmentsRandomly(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int seg1 = randomIndex(BOARD_SEGMENTS_NUMBER);
int seg2 = randomIndex(BOARD_SEGMENTS_NUMBER);
return swapRowSegments(sudokuBoard, seg1, seg2);
}
/**
* Swapping 2 column segments (9x3 each one) of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @param colSeg1 First column segment id: 0, 1, 2.
* @param colSeg2 Second column segment id: 0, 1, 2.
* @return New array containing values resulted form swapping
* column segments procedure. If both segments are equal
* or one of the segments id is not 0, 1, or 2, then exact
* copy of original board is returned.
*/
public static final int[][] swapColSegments(int[][] sudokuBoard, int colSeg1, int colSeg2) {
if (sudokuBoard == null) return null;
int[][] newBoard = boardCopy(sudokuBoard);
if (colSeg1 == colSeg2) return newBoard;
if ( (colSeg1 < 0) || (colSeg1 > 2) ) return newBoard;
if ( (colSeg2 < 0) || (colSeg2 > 2) ) return newBoard;
int startColSeg1 = boardSegmentStartIndex(colSeg1);
int startColSeg2 = boardSegmentStartIndex(colSeg2);
for (int j = 0; j < BOARD_SUB_SQURE_SIZE; j++)
for (int i = 0; i < BOARD_SIZE; i++) {
newBoard[i][startColSeg1 + j] = sudokuBoard[i][startColSeg2 + j];
newBoard[i][startColSeg2 + j] = sudokuBoard[i][startColSeg1 + j];
}
return newBoard;
}
/**
* Swapping randomly selected 2 column segments (9x3 each one) of Sudoku board.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array containing values resulted form swapping
* column segments procedure.
*/
public static final int[][] swapColSegmentsRandomly(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int seg1 = randomIndex(BOARD_SEGMENTS_NUMBER);
int seg2 = randomIndex(BOARD_SEGMENTS_NUMBER);
return swapColSegments(sudokuBoard, seg1, seg2);
}
/**
* Swapping 2 rows within a given row segment.
*
* @param sudokuBoard Array representing Sudoku board.
* @param rowSeg Row segment id: 0, 1, 2.
* @param row1 First row id within a segment: 0, 1, 2.
* @param row2 Second row id within a segment: 0, 1, 2.
* @return New array containing values resulted form swapping
* rows procedure. If both rows are equal
* or one of the row id is not 0, 1, or 2, then exact
* copy of original board is returned.
*/
public static final int[][] swapRowsInSegment(int[][] sudokuBoard, int rowSeg, int row1, int row2) {
if (sudokuBoard == null) return null;
int[][] newBoard = boardCopy(sudokuBoard);
if ( (rowSeg < 0) || (rowSeg > 2) ) return newBoard;
if ( (row1 < 0) || (row1 > 2) ) return newBoard;
if ( (row2 < 0) || (row2 > 2) ) return newBoard;
if (row1 == row2) return newBoard;
int segStart = boardSegmentStartIndex(rowSeg);
for (int j = 0; j < BOARD_SIZE; j++) {
newBoard[segStart + row1][j] = sudokuBoard[segStart + row2][j];
newBoard[segStart + row2][j] = sudokuBoard[segStart + row1][j];
}
return newBoard;
}
/**
* Swapping randomly selected 2 rows within randomly select row segment.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array containing values resulted form swapping
* column segments procedure.
*/
public static final int[][] swapRowsInSegmentRandomly(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int rowSeg = randomIndex(BOARD_SEGMENTS_NUMBER);
int row1 = randomIndex(BOARD_SUB_SQURE_SIZE);
int row2 = randomIndex(BOARD_SUB_SQURE_SIZE);
return swapRowsInSegment(sudokuBoard, rowSeg, row1, row2);
}
/**
* Swapping 2 columns within a given column segment.
*
* @param sudokuBoard Array representing Sudoku board.
* @param colSeg Column segment id: 0, 1, 2.
* @param col1 First column id within a segment: 0, 1, 2.
* @param col2 Second column id within a segment: 0, 1, 2.
* @return New array containing values resulted form swapping
* columns procedure. If both columns are equal
* or one of the id is not 0, 1, or 2, then exact
* copy of original board is returned.
*/
public static final int[][] swapColsInSegment(int[][] sudokuBoard, int colSeg, int col1, int col2) {
if (sudokuBoard == null) return null;
int[][] newBoard = boardCopy(sudokuBoard);
if ( (colSeg < 0) || (colSeg > 2) ) return newBoard;
if ( (col1 < 0) || (col1 > 2) ) return newBoard;
if ( (col2 < 0) || (col2 > 2) ) return newBoard;
if (col1 == col2) return newBoard;
int segStart = boardSegmentStartIndex(colSeg);
for (int i = 0; i < BOARD_SIZE; i++) {
newBoard[i][segStart + col1] = sudokuBoard[i][segStart + col2];
newBoard[i][segStart + col2] = sudokuBoard[i][segStart + col1];
}
return newBoard;
}
/**
* Swapping randomly selected 2 columns within randomly select column segment.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array containing values resulted form swapping
* column segments procedure.
*/
public static final int[][] swapColsInSegmentRandomly(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
int colSeg = randomIndex(BOARD_SEGMENTS_NUMBER);
int col1 = randomIndex(BOARD_SUB_SQURE_SIZE);
int col2 = randomIndex(BOARD_SUB_SQURE_SIZE);
return swapColsInSegment(sudokuBoard, colSeg, col1, col2);
}
/*
* ======================================================
* Permutation methods
* ======================================================
*/
/**
* Sudoku board permutation.
* @param sudokuBoard Sudoku board to be permuted.
* @param permutation Permutation (ie. 5, 2, 8, 9, 1, 3, 6, 4, 7)
* @return If board is null then null,
* If permutation is not valid the original board.
* Otherwise permuted board.
*/
public static final int[][] permuteBoard(int[][] sudokuBoard, int[] permutation) {
if (sudokuBoard == null) return null;
if (isValidPermutation(permutation, BOARD_SIZE) == false) return boardCopy(sudokuBoard);
int[][] permutatedBoard = new int[BOARD_SIZE][BOARD_SIZE];
for (int i = 0; i < BOARD_SIZE; i++)
for (int j = 0; j < BOARD_SIZE; j++) {
int digit = sudokuBoard[i][j];
if (digit == BoardCell.EMPTY)
permutatedBoard[i][j] = BoardCell.EMPTY;
else
permutatedBoard[i][j] = permutation[digit-1]+1;
}
return permutatedBoard;
}
/**
* Random permutation of sudoku board.
*
* @param sudokuBoard Sudoku board to be permuted.
* @return If sudoku board is ot null then permuted board,
* otherwise null.
*/
public static final int[][] permuteBoard(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
return permuteBoard(sudokuBoard, generatePermutation(BOARD_SIZE));
}
/**
* Method applies given permutation of length 3 (permutation of 0, 1, 2)
* to the 3 row segments (3x9 each one) of Sudoku array.
*
* @param sudokuBoard Array representing Sudoku board.
* @param permutation Array representing permutation of length 3 (permuting: 0, 1, 2).
* @return New array resulting from permutation of given sudokuBoard. If sudokuBoard is null
* the null is returned. If permutation is not valid copy of original Sudoku board
* is returned.
*/
public static final int[][] permuteRowSegments(int[][] sudokuBoard, int[] permutation) {
if (sudokuBoard == null) return null;
if (isValidPermutation(permutation, BOARD_SEGMENTS_NUMBER) == false) return boardCopy(sudokuBoard);
int[][] permutatedBoard = new int[BOARD_SIZE][BOARD_SIZE];
int[] segmentStart = new int[BOARD_SEGMENTS_NUMBER];
for (int seg = 0; seg < BOARD_SEGMENTS_NUMBER; seg ++)
segmentStart[seg] = boardSegmentStartIndex(seg);
for (int seg = 0; seg < BOARD_SEGMENTS_NUMBER; seg++)
for (int i = 0; i < BOARD_SUB_SQURE_SIZE; i++) {
int curRowIndex = segmentStart[ permutation[seg] ] + i;
int newRowIndex = segmentStart[seg] + i;
for (int j = 0; j < BOARD_SIZE; j++) {
permutatedBoard[newRowIndex][j] = sudokuBoard[curRowIndex][j];
}
}
return permutatedBoard;
}
/**
* Method applies randomly generated permutation of length 3 (permutation of 0, 1, 2)
* to the 3 row segments (3x9 each one) of Sudoku array.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array resulting from permutation of given sudokuBoard. If sudokuBoard is null
* the null is returned.
*/
public static final int[][] permuteRowSegments(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
return permuteRowSegments(sudokuBoard, generatePermutation(BOARD_SEGMENTS_NUMBER) );
}
/**
* Method applies given permutation of length 3 (permutation of 0, 1, 2)
* to the 3 column segments (9x3 each one) of Sudoku array.
*
* @param sudokuBoard Array representing Sudoku board.
* @param permutation Array representing permutation of length 3 (permuting: 0, 1, 2).
* @return New array resulting from permutation of given sudokuBoard. If sudokuBoard is null
* the null is returned. If permutation is not valid copy of original Sudoku board
* is returned.
*/
public static final int[][] permuteColSegments(int[][] sudokuBoard, int[] permutation) {
if (sudokuBoard == null) return null;
if (isValidPermutation(permutation, BOARD_SEGMENTS_NUMBER) == false) return boardCopy(sudokuBoard);
int[][] permutatedBoard = new int[BOARD_SIZE][BOARD_SIZE];
int[] segmentStart = new int[BOARD_SEGMENTS_NUMBER];
for (int seg = 0; seg < BOARD_SEGMENTS_NUMBER; seg ++)
segmentStart[seg] = boardSegmentStartIndex(seg);
for (int seg = 0; seg < BOARD_SEGMENTS_NUMBER; seg++)
for (int j = 0; j < BOARD_SUB_SQURE_SIZE; j++) {
int curColIndex = segmentStart[ permutation[seg] ] + j;
int newColIndex = segmentStart[seg] + j;
for (int i = 0; i < BOARD_SIZE; i++) {
permutatedBoard[i][newColIndex] = sudokuBoard[i][curColIndex];
}
}
return permutatedBoard;
}
/**
* Method applies randomly generated permutation of length 3 (permutation of 0, 1, 2)
* to the 3 column segments (9x3 each one) of Sudoku array.
*
* @param sudokuBoard Array representing Sudoku board.
* @return New array resulting from permutation of given sudokuBoard. If sudokuBoard is null
* the null is returned.
*/
public static final int[][] permuteColSegments(int[][] sudokuBoard) {
if (sudokuBoard == null) return null;
return permuteColSegments(sudokuBoard, generatePermutation(BOARD_SEGMENTS_NUMBER) );
}
/**
* Method applies given permutation of length 3 (permutation of 0, 1, 2)
* to the 3 rows in a given row segment (9x3 each one) of Sudoku array.
*
* @param sudokuBoard Array representing Sudoku board.
* @param rowSeg Row segment id: 0, 1, 2.