-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSudokuGenerator.java
More file actions
88 lines (77 loc) · 2.47 KB
/
SudokuGenerator.java
File metadata and controls
88 lines (77 loc) · 2.47 KB
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
import java.util.Random;
public class SudokuGenerator {
private static final int SIZE = 9;
private static final int SUBGRID = 3;
private int[][] board = new int[SIZE][SIZE];
private Random rand = new Random();
public int[][] generateFullBoard() {
fillBoard(0, 0);
return board;
}
private boolean fillBoard(int row, int col) {
if (row == SIZE)
return true;
if (col == SIZE)
return fillBoard(row + 1, 0);
int[] nums = shuffleArray();
for (int num : nums) {
if (isSafe(row, col, num)) {
board[row][col] = num;
if (fillBoard(row, col + 1))
return true;
board[row][col] = 0;
}
}
return false;
}
private int[] shuffleArray() {
int[] arr = new int[SIZE];
for (int i = 0; i < SIZE; i++)
arr[i] = i + 1;
for (int i = SIZE - 1; i > 0; i--) {
int j = rand.nextInt(i + 1);
int temp = arr[i];
arr[i] = arr[j];
arr[j] = temp;
}
return arr;
}
private boolean isSafe(int row, int col, int num) {
for (int i = 0; i < SIZE; i++) {
if (board[row][i] == num || board[i][col] == num)
return false;
}
int startRow = row - row % SUBGRID;
int startCol = col - col % SUBGRID;
for (int i = 0; i < SUBGRID; i++) {
for (int j = 0; j < SUBGRID; j++) {
if (board[startRow + i][startCol + j] == num)
return false;
}
}
return true;
}
public int[][] generatePuzzleBoard(Difficulty level) {
int[][] puzzleBoard = deepCopy(board);
removeCells(puzzleBoard, level.getCellsToRemove());
return puzzleBoard;
}
private void removeCells(int[][] puzzleBoard, int cellsToRemove) {
int count = 0;
while (count < cellsToRemove) {
int row = rand.nextInt(9);
int col = rand.nextInt(9);
if (puzzleBoard[row][col] != 0) {
puzzleBoard[row][col] = 0;
count++;
}
}
}
private int[][] deepCopy(int[][] original) {
int[][] copy = new int[original.length][original[0].length];
for (int i = 0; i < original.length; i++) {
System.arraycopy(original[i], 0, copy[i], 0, original[0].length);
}
return copy;
}
}