저는 스도쿠 퍼즐 생성기를 자바로 사용하기 위해이 클래스를 작성하여 퍼즐을 생성했지만 정확하게 퍼즐을 생성하지는 않습니다. 여기에 내가 무엇입니까 무엇의 예입니다Java 스도쿠 생성기가 올바르게 작동하지 않습니다.
이 유효한 스도쿠 솔루션이 아닙니다 볼 수 있듯이. 그러나 내 코드를 살펴보면 왜 이것이 유효한 퍼즐을 생성하지 않는지 이해할 수 없습니다. 누군가 이것이 왜 제대로 작동하지 않는지 설명 할 수 있습니까?
package sudoku;
import java.util.Random;
public class Puzzle {
// number generator
Random gen = new Random();
// 9x9 puzzle
int puzzle[][] = new int[9][9];
public int[][] generate() {
// add each number to the board
for (int x = 0; x < 9; x++) {
for (int y = 0; y < 9; y++) {
boolean isValid = false;
// keep generating new numbers until a valid number is found
while (isValid == false) {
// generate random number 1-9
int num = gen.nextInt(9) + 1;
// check if number is valid
if (checkRow(num, x) == true || checkCol(num, y) == true
|| checkSection(num, x, y) == true) {
// add number to the board
puzzle[x][y] = num;
// exit loop
isValid = true;
}
}
}
}
return puzzle;
}
// check each element of the row for num, if num is found return false
private boolean checkRow(int num, int row) {
boolean valid = true;
for (int i = 0; i < 9; i++) {
if (puzzle[row][i] == num) {
valid = false;
break;
}
}
return valid;
}
// check each element of the column for num, if num is found return false
private boolean checkCol(int num, int col) {
boolean valid = true;
for (int i = 0; i < 9; i++) {
if (puzzle[i][col] == num) {
valid = false;
break;
}
}
return valid;
}
// check each element of the section for num, if num is found return false
private boolean checkSection(int num, int xPos, int yPos) {
int[][] section = new int[3][3];
section = getSection(xPos, yPos);
boolean valid = true;
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
if (section[i][j] == num) {
valid = false;
break;
}
}
}
return valid;
}
// return the 3x3 section the given coordinates are in
private int[][] getSection(int xPos, int yPos) {
int xIndex = 0;
int yIndex = 0;
int[][] section = new int[3][3];
// get x index
if (xPos == 0 || xPos == 3 || xPos == 6) {
xIndex = xPos;
} else if (xPos == 1 || xPos == 4 || xPos == 7) {
xIndex = xPos - 1;
} else if (xPos == 2 || xPos == 5 || xPos == 8) {
xIndex = xPos - 2;
}
// get y index
if (yPos == 0 || yPos == 3 || yPos == 6) {
yIndex = yPos;
} else if (yPos == 1 || yPos == 4 || yPos == 7) {
yIndex = yPos - 1;
} else if (yPos == 2 || yPos == 5 || yPos == 8) {
yIndex = yPos - 2;
}
int i = 0;
int j = 0;
// extract section from puzzle
for (int x = xIndex; x < 3; x++) {
for (int y = yIndex; y < 3; y++) {
section[x][y] = puzzle[i][j];
i++;
}
j++;
}
return section;
}
}
귀하의 클래스는 완전히 절차 적으로 작성되었으며, 개체 오리엔테이션의 흔적은 없습니다. 알고리즘을 객체로 모듈화하면 문제를 해결하기가 더 쉽다는 것을 알 수 있습니다. 각각의 자체 메소드를 테스트하고 구성합니다. 프로젝트의 명사는 퍼즐, 섹션, 사각형입니다. 아마도 열과 행 및 자릿수. 수업과 같은 소리. 엄청난 모 놀리 식 프로 시저를 디버깅하는 대신 개별 모듈의 동작을 디버그하는 것이 더 쉬울 것입니다. – scottb
이것은 오류가 아니지만'if (someCondition == true)''== true '부분이 중복되고, 간단한 경우'(someCondition)'이면 충분합니다. – Pshemo