0
다음 클래스를 작성하여 스도쿠 격자를 생성했습니다. 나는 프로그램의 결과 중 일부를 이해할 수 없다. 아무도 설명 할 수 있을까요?스도쿠 격자를 생성 할 때 예기치 않은 결과가 발생했습니다.
public class SudokuUtility {
static final int max = 8;
static final int min = 0;
static final int digitMax = 9;
static final int digitMin = 0;
static final int easyMin = 36;
static final int easyMax = 49;
static final int mediumMin = 32;
static final int mediumMax = 40;
static final int hardMin = 22;
static final int hardMax = 30;
public static int[][] makeAGrid(String option) {
int[][] grid = new int[9][9];
option = "hard";
Random random = new Random();
int row = 0;
int col = 0;
int randomNumber = 0;
int noOfCellsToBeGenerated = 0;
if ("easy".equals(option)) {
noOfCellsToBeGenerated = random.nextInt((easyMax - easyMin) + 1) + easyMin;
} else if ("medium".equals(option)) {
noOfCellsToBeGenerated = random.nextInt((mediumMax - mediumMin) + 1) + mediumMin;
} else {
noOfCellsToBeGenerated = random.nextInt((hardMax - hardMin) + 1) + hardMin;
}
for (int i = 1; i <= noOfCellsToBeGenerated; i++) {
row = random.nextInt((max - min) + 1) + min;
col = random.nextInt((max - min) + 1) + min;
randomNumber = random.nextInt((digitMax - digitMin) + 1) + digitMin;
if (noConflict(grid, row, col, randomNumber)) {
grid[row][col] = randomNumber;
} else {
i = i - 1; // Nullify this iteration
}
}
int zeroCount = 0;
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (grid[i][j] == 0) {
zeroCount++;
}
System.out.print(grid[i][j] + " ");
}
System.out.println();
}
System.out.println("No of zeros in the " + option + " puzzle = " + zeroCount + " and noOfCellsGenerated = " + noOfCellsToBeGenerated);
return grid;
}
public static boolean noConflict(int[][] array, int row, int col, int num) {
for (int i = 0; i < 9; i++) {
if (array[row][i] == num) {
return false;
}
if (array[i][col] == num) {
return false;
}
}
int gridRow = row - (row % 3);
int gridColumn = col - (col % 3);
for (int p = gridRow; p < gridRow + 3; p++) {
for (int q = gridColumn; q < gridColumn + 3; q++) {
if (array[p][q] == num) {
return false;
}
}
}
return true;
}
}
출력은 :
가0 6 0 0 0 1 0 7 0
0 9 0 4 0 0 0 1 0
0 8 0 0 3 0 0 0 0
0 0 0 7 0 0 0 0 0
9 0 0 8 0 0 0 0 0
0 7 0 0 6 0 2 0 0
7 5 0 0 0 0 0 0 9
8 0 0 0 4 0 0 0 0
0 1 0 0 7 0 0 6 0
No of zeros in the hard puzzle = 59 and noOfCellsGenerated = 24
24 생성 수있을 것이다. 사실 21이 있습니다. 내 논리가 잘못 되었나요? 그러나 저는 그 논리에 대해 확신합니다. 내 이해에 빠진 것은 무엇인가?
동일한 셀 (행, 열)을 두 번 누르는 경우 어떻게됩니까? 이미 숫자가 포함되어 있다면 말입니다. – enlait
@enlait 나는 그 반복을 무효화했다. –
그래서 그것은 4 번 일어 났고 그 차이를 설명합니다. – helderdarocha