I'm trying to generate a complete (ie, each cell filled with a number) Sudoku-like board. It's for something else that has nothing to do with sudokus, so I am not interested in reaching a sudoku with white squares that can be solved, or anything that has to do with sudokus. Don't know if you know what I mean.
I've done this in java:
private int sudokuNumberSelector(int x, int y, int[][] sudoku) {
boolean valid = true;
String validNumbers = new String();
int[] aValidNumbers;
int squarexstart = 0;
int squareystart = 0;
int b = 0; // For random numbers
Random randnum = new Random();
randnum.setSeed(new Date().getTime());
// Check numbers one by one
for(int n = 1; n < 10; n++) {
valid = true;
// Check column
for(int i = 0; i < 9; i++) {
if(sudoku[i][y] == n) {
valid = false;
}
}
// Check file
for(int j = 0; j < 9; j++) {
if(sudoku[x][j] == n) {
valid = false;
}
}
// Check square
switch (x) {
case 0: case 1: case 2: squarexstart = 0; break;
case 3: case 4: case 5: squarexstart = 3; break;
case 6: case 7: case 8: squarexstart = 6; break;
}
switch (y) {
case 0: case 1: case 2: squareystart = 0; break;
case 3: case 4: case 5: squareystart = 3; break;
case 6: case 7: case 8: squareystart = 6; break;
}
for(int i = squarexstart; i < (squarexstart + 3); i++ ) {
for(int j = squareystart; j < (squareystart + 3); j++ ) {
if(sudoku[i][j] == n) {
valid = false;
}
}
}
// If the number is valid, add it to the String
if(valid) {
validNumbers += n;
}
}
if(validNumbers.length() != 0) {
// String to int[]
aValidNumbers = fromPuzzleString(validNumbers);
// By this random number, return the valid number in its position
Log.d(TAG, "NUMBERS: " + validNumbers.length());
// Select a random number from the int[]
b = randnum.nextInt((aValidNumbers.length));
return aValidNumbers[b];
} else {
return 0;
}
}
This method is called from this piece of code:
int[][] sudoku = new int[9][9];
for(int i = 0; i < 9; i++) {
for(int j = 0; j < 9; j++) {
sudoku[i][j] = sudokuNumberSelector(i, j, sudoku);
}
}
But it is not as easy as it seemed! When the algorithm has generated a part of the board like this one, and the loop is on the cell on bold:
|||164527389|||
|||983416257|||
|||257938416|||
|||719352648|||
|||3256791**0**0|||
|||000000000|||
|||000000000|||
|||000000000|||
|||000000000|||
There are no numbers to put in this cell, because all the numbers according to the rules of sudoku are already on the column, row or square!
It is a nightmare for me. Is there any way to this to work? If not, i guess I have to redo everything as if I were making a Sudoku game.
The problem is that it is not possible to generate a complete board using random numbers in most cases, you have to use backtracking in cases when it is not possibe to fi the next cell.
I have once written a sudoku game, so here's the piece of code that generates filled board.
This is the Cell class.
public class SudokuCell implements Serializable {
private int value;
private boolean filled;
private HashSet<Integer> tried;
public SudokuCell() {
filled = false;
tried = new HashSet();
}
public boolean isFilled() {
return filled;
}
public int get() {
return value;
}
public void set(final int number) {
filled = true;
value = number;
tried.add(number);
}
public void clear() {
value = 0;
filled = false;
}
public void reset() {
clear();
tried.clear();
}
public void show() {
filled = true;
}
public void hide() {
filled = false;
}
public boolean isTried(final int number) {
return tried.contains(number);
}
public void tryNumber(final int number) {
tried.add(number);
}
public int numberOfTried() {
return tried.size();
}
}
Here's the Field class (it's really handy to keep all data in just one object).
public class SudokuField implements Serializable {
private final int blockSize;
private final int fieldSize;
private SudokuCell[][] field;
public SudokuField(final int blocks) {
blockSize = blocks;
fieldSize = blockSize * blockSize;
field = new SudokuCell[fieldSize][fieldSize];
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
field[i][j] = new SudokuCell();
}
}
}
public int blockSize() {
return blockSize;
}
public int fieldSize() {
return fieldSize;
}
public int variantsPerCell() {
return fieldSize;
}
public int numberOfCells() {
return fieldSize * fieldSize;
}
public void clear(final int row, final int column) {
field[row - 1][column - 1].clear();
}
public void clearAllCells() {
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
field[i][j].clear();
}
}
}
public void reset(final int row, final int column) {
field[row - 1][column - 1].reset();
}
public void resetAllCells() {
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
field[i][j].reset();
}
}
}
public boolean isFilled(final int row, final int column) {
return field[row - 1][column - 1].isFilled();
}
public boolean allCellsFilled() {
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
if (!field[i][j].isFilled()) {
return false;
}
}
}
return true;
}
public int numberOfFilledCells() {
int filled = 0;
for (int i = 1; i <= fieldSize; ++i) {
for (int j = 1; j <= fieldSize; ++j) {
if (isFilled(i, j)) {
++filled;
}
}
}
return filled;
}
public int numberOfHiddenCells() {
return numberOfCells() - numberOfFilledCells();
}
public int get(final int row, final int column) {
return field[row - 1][column - 1].get();
}
public void set(final int number, final int row, final int column) {
field[row - 1][column - 1].set(number);
}
public void hide(final int row, final int column) {
field[row - 1][column - 1].hide();
}
public void show(final int row, final int column) {
field[row - 1][column - 1].show();
}
public void tryNumber(final int number, final int row, final int column) {
field[row - 1][column - 1].tryNumber(number);
}
public boolean numberHasBeenTried(final int number, final int row, final int column) {
return field[row - 1][column - 1].isTried(number);
}
public int numberOfTriedNumbers(final int row, final int column) {
return field[row - 1][column - 1].numberOfTried();
}
public boolean checkNumberBox(final int number, final int row, final int column) {
int r = row, c = column;
if (r % blockSize == 0) {
r -= blockSize - 1;
} else {
r = (r / blockSize) * blockSize + 1;
}
if (c % blockSize == 0) {
c -= blockSize - 1;
} else {
c = (c / blockSize) * blockSize + 1;
}
for (int i = r; i < r + blockSize; ++i) {
for (int j = c; j < c + blockSize; ++j) {
if (field[i - 1][j - 1].isFilled() && (field[i - 1][j - 1].get() == number)) {
return false;
}
}
}
return true;
}
public boolean checkNumberRow(final int number, final int row) {
for (int i = 0; i < fieldSize; ++i) {
if (field[row - 1][i].isFilled() && field[row - 1][i].get() == number) {
return false;
}
}
return true;
}
public boolean checkNumberColumn(final int number, final int column) {
for (int i = 0; i < fieldSize; ++i) {
if (field[i][column - 1].isFilled() && field[i][column - 1].get() == number) {
return false;
}
}
return true;
}
public boolean checkNumberField(final int number, final int row, final int column) {
return (checkNumberBox(number, row, column)
&& checkNumberRow(number, row)
&& checkNumberColumn(number, column));
}
public int numberOfPossibleVariants(final int row, final int column) {
int result = 0;
for (int i = 1; i <= fieldSize; ++i) {
if (checkNumberField(i, row, column)) {
++result;
}
}
return result;
}
public boolean isCorrect() {
for (int i = 0; i < fieldSize; ++i) {
for (int j = 0; j < fieldSize; ++j) {
if (field[i][j].isFilled()) {
int value = field[i][j].get();
field[i][j].hide();
boolean correct = checkNumberField(value, i + 1, j + 1);
field[i][j].show();
if (!correct) {
return false;
}
}
}
}
return true;
}
public Index nextCell(final int row, final int column) {
int r = row, c = column;
if (c < fieldSize) {
++c;
} else {
c = 1;
++r;
}
return new Index(r, c);
}
public Index cellWithMinVariants() {
int r = 1, c = 1, min = 9;
for (int i = 1; i <= fieldSize; ++i) {
for (int j = 1; j <= fieldSize; ++j) {
if (!field[i - 1][j - 1].isFilled()) {
if (numberOfPossibleVariants(i, j) < min) {
min = numberOfPossibleVariants(i, j);
r = i;
c = j;
}
}
}
}
return new Index(r, c);
}
public int getRandomIndex() {
return (int) (Math.random() * 10) % fieldSize + 1;
}
}
And finally the function that fills the game board
private void generateFullField(final int row, final int column) {
if (!field.isFilled(field.fieldSize(), field.fieldSize())) {
while (field.numberOfTriedNumbers(row, column) < field.variantsPerCell()) {
int candidate = 0;
do {
candidate = field.getRandomIndex();
} while (field.numberHasBeenTried(candidate, row, column));
if (field.checkNumberField(candidate, row, column)) {
field.set(candidate, row, column);
Index nextCell = field.nextCell(row, column);
if (nextCell.i <= field.fieldSize()
&& nextCell.j <= field.fieldSize()) {
generateFullField(nextCell.i, nextCell.j);
}
} else {
field.tryNumber(candidate, row, column);
}
}
if (!field.isFilled(field.fieldSize(), field.fieldSize())) {
field.reset(row, column);
}
}
}
The point is that you save the numbers you've already tried for each cell before moving on. If you have to the dead end, you simply need to try another number for the previous cell. If none are possible, erase that cell and step one cell back. Sooner or later you will get it done. (It actuay takes tiny amount of time).
Start out with a solved Sudoko like this:
ABC DEF GHI
329 657 841 A
745 831 296 B
618 249 375 C
193 468 527 D
276 195 483 E
854 372 619 F
432 716 958 G
587 923 164 H
961 584 732 I
And then permutate it by switching columns and switching rows. If you only switch within the following groups ABC, DEF, GHI, the Sudoku is still solved.
A permutated version (switching columns):
BCA DFE IGH
293 675 184 A
457 813 629 B
186 294 537 C
931 486 752 D
762 159 348 E
548 327 961 F
324 761 895 G
875 932 416 H
619 548 273 I
And after some more permutation (switching rows):
BCA DFE IGH
293 675 184 A
186 294 537 C
457 813 629 B
931 486 752 D
548 327 961 F
762 159 348 E
875 932 416 H
619 548 273 I
324 761 895 G
Your problem is you are using Strings. Try a recursive algorithm using integers. This algorithm will be useful for a sudoku of any size. While choosing random numbers within each call does work, it'll take much longer. If you choose a set of random numbers to go through if the next cell doesnt work, then you will not use the same number again. This algorithm will create a unique puzzle every time.
public class Sudoku {
//box size, and game SIZE ==> e.g. size = 3, SIZE = 9
//game will be the game
private int size, SIZE;
private int[][] game;
public Sudoku(int _size) {
size = _size;
SIZE = size*size;
game = generateGame();
}
//This will return the game
private int[][] generateGame() {
//Set everything to -1 so that it cannot be a value
int[][] g = new int[SIZE][SIZE];
for(int i = 0; i < SIZE; i++)
for(int j = 0; j < SIZE; j++)
g[i][j] = -1;
if(createGame(0, 0, g))
return g;
return null;
}
//Create the game
private boolean createGame(int x, int y, int[][] g) {
//An array of integers
Rand r = new Rand(SIZE);
//for every random num in r
for(int NUM = 0; NUM < size; NUM++) {
int num = r.get(NUM);
//if num is valid
if(isValid(x, y, g, num)) {
//next cell coordinates
int nx = (x+1)%SIZE, ny = y;
if(nx == 0) ny++;
//set this cell to num
g[x][y] = num;
//if the next cell is valid return true
if(createGame(nx, ny, g)) return true;
//otherwise return false
g[x][y] = -1;
return false;
}
}
return false;
}
private boolean isValid(int x, int y, int[][] g, int num) {
//Rows&&Cols
for(int i = 0; i < SIZE; i++)
if(g[i][y] == num || g[x][i] == num) return false;
//Box
int bx = x - x%size;, by = y - y%size;
for(int i = bx; i < bx + size; i++) {
for(int j = by; j < by + size; j++) {
if(g[i][j] == num)return false;
}
}
return true;
}
}
public class Rand {
private int rSize;
private int[] r;
public Rand(int _size) {
rSize = _size;
r = new int[size];
for(int i = 0; i < rSize; r++)r[i] = i;
for(int i = 0; i < rSize*5; r++) {
int a = (int)(Math.random()*rSize);
int b = (int)(Math.random()*rSize);
int n = r[a];
r[a] = r[b];
r[b] = n;
}
public void get(int i) {
if(i >= 0 && i < rSize) return r[i]; return -1;
}
}
You're going to have to implement a backtracking algorithm.
For each of the 81 locations, generate the set 1 through 9.
Repeat until solved
Solve one location. Pick one number from the set.
Remove that number from all the sets in the same row, column, and square.
If a conflict arises, backtrack to a known good position, and solve a different location.
You will probably have to use recursive functions so that you can backtrack.
You have at least few ways to do that, but usually you will need recurrence / backtracking. It would be great to have the solver also, just to check if partly filled puzzle has solution (and the unique one - for stoping criteria - if you want the real sudoku).
While performing backtracking / recurrence you will need:
to randomly select available empty cell (you can optimize this step by measuring digidts still free on the given cell, and then sorting)
to randomly select still available digit in that cell
you fill the cell and check if the solution exists, if yes - go further, if not - perform the step back.
Starting points:
- starting with completely empty puzzle
- starting with partially filled puzzle
- starting with solved puzzle (there are a lot of transformations not changing the solution existence, but making the puzzle different - i.e.: reflection, rotation, transposition, segment swapping, columns / rows swapping within segments, permutation, etc.)
I was recently using the Janet Sudoku library which provides solver, generator and puzzle transformation methods.
Janet Sudoku website
Please refer to the below source codes available on the GitHub
Sudoku Solver
Sudoku Generator
Sudoku Transformations
Library usage is pretty simple, ie:
SudokuGenerator g = new SudokuGenerator();
int[][] puzzle = g.generate();
SudokuSolver s = new SudokuSolver(puzzle);
s.solve();
int[][] solvedPuzzle = s.getSolvedBoard();
Best regards,
Just generate some random number between 1 to 9 and see it it fits the given cell[i][j] it promises you a new set of numbers every time as every cell number is generated randomly based on the current system time .
public int sudokuNumberSelector(int i, int j, int[][] sudoku) {
while (true) {
int temp = (int) ((System.currentTimeMillis()) % 9) + 1;//Just getting some random number
while (temp < 10) {
boolean setRow = false, setColomn = false, setBlock = false;
for (int a = 0; a < 9; a++) {
if (sudoku[a][j] == temp) {
setRow = true;
break;
}
}
for (int a = 0; a < 9; a++) {
if (sudoku[i][a] == temp) {
setColomn = true;
break;
}
}
for (int a = i - (i % 3); a < i - (i % 3)+ 3; a++) {
for (int b = j - (j % 3); b < j - (j % 3)+3; b++) {
if (sudoku[a][b] == temp) {
setBlock = true;
a = 3;
b = 3;
}
}
}
if(setRow | setColomn | setBlock == false){
return temp;
}
temp++;
}
}
}
Related
I want to calculoate the determinant of a given NxN Matrix using the Laplace-Method. I already tried differnt approaches which always return a 0.
The class I used:
package Matrix;
import java.io.BufferedReader;
import java.io.FileReader;
import java.util.Scanner;
public class Matrix
{
double[][] array;
public static void init(Matrix a,int row , int column)
{
a.array = new double [row] [column];
for (int i = 0; i < row; i++)
{
for(int k = 0; k < column; k++)
{
a.array[i][k] = 0;
}
}
}
public static int getNRows(Matrix a)
{
return a.array.length;
}
public static int getNColumns(Matrix a)
{
return a.array[0].length;
}
public static void print(Matrix a)
{
for(int i = 0; i < getNRows(a);i++ )
{
for (int k = 0; k < getNColumns(a); k++)
{
System.out.print(a.array[i][k] + "\t");
}
System.out.println();
}
}
public static double det(Matrix a)
{
double det = 0;
det = a.array[0][0] * a.array[1][1] * a.array[2][2] + a.array[1][0] * a.array[2][1] * a.array[0][2] + a.array[2][0] * a.array[0][1] * a.array[1][2] - a.array[2][0] * a.array[1][1] * a.array[0][2] - a.array[1][0] * a.array[0][1] * a.array[2][2] - a.array[0][0] * a.array[2][1] * a.array[1][2];
return det;
public static Matrix transpose(Matrix a)
{
Matrix transposed = new Matrix();
Matrix.init(transposed, getNRows(a), getNColumns(a));
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
transposed.array[j][i] = a.array[i][j];
}
}
return transposed;
}
public static Matrix subMatrix(Matrix a, int exclRow, int exclCol)
{
Matrix subMatrix = new Matrix();
Matrix.init(subMatrix, getNRows(a) - 1, getNColumns(a) - 1);
for(int i = 0; i < getNRows(a) - 1; i++)
{
for(int j = 0; j < getNColumns(a) - 1; j++)
{
if(i != exclRow && j != exclCol)
{
subMatrix.array[i][j] = a.array[i][j];
}
}
}
return subMatrix;
}
public static Matrix loadMatrix(String filename) throws Exception
{
Scanner sc = new Scanner(new BufferedReader(new FileReader(filename)));
Matrix result = new Matrix();
int row = 0;
int col = 0;
String[] line = sc.nextLine().trim().split("\t");
row = Integer.parseInt(line[0]);
col = Integer.parseInt(line[1]);
init(result, row, col);
int currentRow = 0;
while(sc.hasNextLine())
{
String[] line2 =sc.nextLine().trim().split("\t");
for(int i = 0; i < col; i++)
{
result.array[currentRow][i] = Double.parseDouble(line2[i]);
}
currentRow++;
}
return result;
}
/*public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
double value = 1;
if(colOfA != rowOfA)
{
return 0;
}
if(colOfA == 1 && rowOfA == 1)
{
return a.array[0][0];
}
else
{
for(int row = 0; row < rowOfA; row++)
{
value += Math.pow(-1, row) * a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}*/
public static double detN(Matrix a)
{
int colOfA = getNColumns(a);
int rowOfA = getNRows(a);
if(colOfA != rowOfA)
{
return 0;
}
if(rowOfA <= 3)
{
return det(a);
}
double value = 0;
for(int row = 0; row < rowOfA; row++)
{
if(row % 2 == 0)
{
value += a.array[row][0] * detN(subMatrix(a, row, 0));
}
else
{
value -= a.array[row][0] * detN(subMatrix(a, row, 0));
}
}
return value;
}
public static Matrix adjointN(Matrix a)
{
int rowOfA = getNRows(a);
int colOfA = getNColumns(a);
Matrix ret = new Matrix();
Matrix.init(ret, rowOfA, colOfA);
for(int row = 0; row < rowOfA; row++)
{
for(int col = 0; col < colOfA; col++)
{
ret.array[row][col] = detN(subMatrix(a, row, col));
}
ret = transpose(ret);
return ret;
}
return ret;
}
public static Matrix inverseN(Matrix a)
{
Matrix inverse = new Matrix();
Matrix.init(inverse, getNRows(a), getNColumns(a));
double pre = 1/detN(a);
inverse = adjointN(a);
for(int i = 0; i < getNRows(a); i++)
{
for(int j = 0; j < getNColumns(a); j++)
{
inverse.array[j][i] = inverse.array[i][j] * pre;
}
}
return inverse;
}
}
I have two versions for detN, which both yield the same result.
This isn't the entire class, because there are some functions that don't belong to this particular question
Here is an approach you could consider(the code is not fully debugged so take with a grain of salt). Finding the determinant is a recursive concept since you are always finding the determinant of a smaller matrix to get the final answer.
//Recursive base function
public static double det(int[][] matrix) {
if(matrix.length == 2)
return ((matrix[0][0] * matrix[1][1]) - (matrix[0][1] * matrix[1][0]));
double determinant = 0;
int mlength = matrix.length - 1;
int[][] newM = new int[mlength][mlength];
for(int i = 0; i < mlength + 1; i++) {
newM = newMatrix(matrix, i);
determinant = determinant + (Math.pow(-1, i) * matrix[0][i]) * det(newM);
}
return determinant;
}
//Format smaller matrix to use in further iteration of above det(int[][]) function
public static int[][] newMatrix(int[][] m, int column) {
int length = m.length - 1;
int[][] newMat = new int[length][length];
for(int i = 1; i < m.length; i++) {
for(int j = 0; j < column; j++)
newMat[i - 1][j] = m[i][j];
for(int k = column + 1; k < m.length; k++)
newMat[i - 1][k - 1] = m[i][k];
}
return newMat;
}
You can adapt to however your Matrix class works.
subMatrix is not really excluding the given row and column - it is just making them zero (not copying) and removing the last row and column...
Printing the matrix will help debug that.
one way: use additional indices for the destination matrix (the sub matrix). Only increment this if a value is really copied. Example: sub.array[k++][l++] = a.array[i][j] inside the if
loop over original matrix
Alternative: if one index is greater than or equal to the index that must be skipped, add 1 to the reading index:
var k = (i>=exclRow) ? i+1 : i;
var l = (j>=exclCol) ? j+1 : j;
sub.array[i][j = a.array[k][l];
code not intended to be complete, just ideas how to solve the problem
This question already has answers here:
What causes a java.lang.ArrayIndexOutOfBoundsException and how do I prevent it?
(26 answers)
Closed 3 years ago.
My sudoku solver replaces "-" with zeros, then solves the puzzle. It works for most puzzles that I've tried, but throws an ArrayIndexOutOfBoundsException for puzzles with a full row of dashes. I've tried tweeking different things to get it to work, but I'm a little lost.
This is what the puzzle looks like.
public static int[][] theArray = new int [9][9];
public static int SIZE = 9;
private static boolean isCompletePuzzle() {
// checks for 0 in rows/cols
for (int i = 0; i <= SIZE; i++) {
for (int j = 0; j <= SIZE; j++) {
if (theArray[i][j] != 0) {
return true;
}
}
}
return false;
}
private static boolean isValidPuzzle(int row, int col, int number) {
// checks rows
for (int i = 0; i < SIZE; i++) {
if (theArray[row][i] == number) {
return true;
}
}
// checks columns
for (int i = 0; i < SIZE; i++) {
if (theArray[i][col] == number) {
return true;
}
}
// checks 3x3
int r = row - row % 3;
int c = col - col % 3;
for (int i = r; i < r + 3; i++)
for (int j = c; j < c + 3; j++)
if (theArray[i][j] == number)
return true;
return false;
}
private static boolean isSolvedPuzzle(int row, int col, int number) {
if (isValidPuzzle(row, col, number) == true && isCompletePuzzle() == true) {
return true;
}
return false;
}
public static boolean solvePuzzle() {
for (int row = 0; row < SIZE; row++) {
for (int col = 0; col < SIZE; col++) {
if (theArray[row][col] == 0) {
for (int number = 1; number <= SIZE; number++) {
if (!isSolvedPuzzle(row, col, number)) {
theArray[row][col] = number;
if (solvePuzzle()) {
return true;
}
else {
theArray[row][col] = 0;
}
}
}
return false;
}
}
}
return true;
}
in ur isCompletePuzzle() function ur loop conditions i <= SIZE and j <= SIZE cause ArrayIndexOutOfBoundsException
when i is 9 the if (theArray[i][j] != 0) throw ArrayIndexOutOfBoundsException
Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I am told that A* implementation on following 8 puzzle Solver is wrong, can anybody please tell me where it's wrong and how to correct it?
Also: this throws Exception in thread "main" java.lang.OutOfMemoryError: Java heap space even though Build Process Heap size is set to 2048.
Here is Solver.java
import java.util.HashSet;
import java.util.Set;
import java.util.Stack;
import java.util.PriorityQueue;
public class Solver {
private int moves = 0;
private SearchNode finalNode;
private Stack<Board> boards;
public Solver(Board initial) {
if (!initial.isSolvable()) throw new IllegalArgumentException("Unsolvable puzzle");
// this.initial = initial;
PriorityQueue<SearchNode> minPQ = new PriorityQueue<SearchNode>(initial.size() + 10);
Set<Board> previouses = new HashSet<Board>(50);
Board dequeuedBoard = initial;
Board previous = null;
SearchNode dequeuedNode = new SearchNode(initial, 0, null);
Iterable<Board> boards;
while (!dequeuedBoard.isGoal()) {
boards = dequeuedBoard.neighbors();
moves++;
for (Board board : boards) {
if (!board.equals(previous) && !previouses.contains(board)) {
minPQ.add(new SearchNode(board, moves, dequeuedNode));
}
}
previouses.add(previous);
previous = dequeuedBoard;
dequeuedNode = minPQ.poll();
dequeuedBoard = dequeuedNode.current;
}
finalNode = dequeuedNode;
}
// min number of moves to solve initial board
public int moves() {
if (boards != null) return boards.size()-1;
solution();
return boards.size() - 1;
}
public Iterable<Board> solution() {
if (boards != null) return boards;
boards = new Stack<Board>();
SearchNode pointer = finalNode;
while (pointer != null) {
boards.push(pointer.current);
pointer = pointer.previous;
}
return boards;
}
private class SearchNode implements Comparable<SearchNode> {
private final int priority;
private final SearchNode previous;
private final Board current;
public SearchNode(Board current, int moves, SearchNode previous) {
this.current = current;
this.previous = previous;
this.priority = moves + current.manhattan();
}
#Override
public int compareTo(SearchNode that) {
int cmp = this.priority - that.priority;
return Integer.compare(cmp, 0);
}
}
public static void main(String[] args) {
int[][] tiles = {{4, 1, 3},
{0, 2, 6},
{7, 5, 8}};
double start = System.currentTimeMillis();
Board board = new Board(tiles);
Solver solve = new Solver(board);
System.out.printf("# of moves = %d && # of actual moves %d & time passed %f\n, ", solve.moves(), solve.moves, (System.currentTimeMillis() - start) / 1000);
}
}
And Board.java, just in case:
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
public final class Board {
private final int[][] tilesCopy;
private final int N;
// cache
private int hashCode = -1;
private int zeroRow = -1;
private int zeroCol = -1;
private Collection<Board> neighbors;
/*
* Rep Invariant
* tilesCopy.length > 0
* Abstraction Function
* represent single board of 8 puzzle game
* Safety Exposure
* all fields are private and final (except cache variables). In the constructor,
* defensive copy of tiles[][] (array that is received from the client)
* is done.
*/
public Board(int[][] tiles) {
//this.N = tiles.length;
this.N = 3;
this.tilesCopy = new int[N][N];
// defensive copy
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
if (tiles[i][j] >= 0 && tiles[i][j] < N*N) tilesCopy[i][j] = tiles[i][j];
else {
System.out.printf("Illegal tile value at (%d, %d): "
+ "should be between 0 and N^2 - 1.", i, j);
System.exit(1);
}
}
}
checkRep();
}
public int tileAt(int row, int col) {
if (row < 0 || row > N - 1) throw new IndexOutOfBoundsException
("row should be between 0 and N - 1");
if (col < 0 || col > N - 1) throw new IndexOutOfBoundsException
("col should be between 0 and N - 1");
return tilesCopy[row][col];
}
public int size() {
return N;
}
public int hamming() {
int hamming = 0;
for (int row = 0; row < this.size(); row++) {
for (int col = 0; col < this.size(); col++) {
if (tileAt(row, col) != 0 && tileAt(row, col) != (row*N + col + 1)) hamming++;
}
}
return hamming;
}
// sum of Manhattan distances between tiles and goal
public int manhattan() {
int manhattan = 0;
int expectedRow = 0, expectedCol = 0;
for (int row = 0; row < this.size(); row++) {
for (int col = 0; col < this.size(); col++) {
if (tileAt(row, col) != 0 && tileAt(row, col) != (row*N + col + 1)) {
expectedRow = (tileAt(row, col) - 1) / N;
expectedCol = (tileAt(row, col) - 1) % N;
manhattan += Math.abs(expectedRow - row) + Math.abs(expectedCol - col);
}
}
}
return manhattan;
}
public boolean isGoal() {
if (tileAt(N-1, N-1) != 0) return false; // prune
for (int i = 0; i < this.size(); i++) {
for (int j = 0; j < this.size(); j++) {
if (tileAt(i, j) != 0 && tileAt(i, j) != (i*N + j + 1)) return false;
}
}
return true;
}
// change i && j' s name
public boolean isSolvable() {
int inversions = 0;
for (int i = 0; i < this.size() * this.size(); i++) {
int currentRow = i / this.size();
int currentCol = i % this.size();
if (tileAt(currentRow, currentCol) == 0) {
this.zeroRow = currentRow;
this.zeroCol = currentCol;
}
for (int j = i; j < this.size() * this.size(); j++) {
int row = j / this.size();
int col = j % this.size();
if (tileAt(row, col) != 0 && tileAt(row, col) < tileAt(currentRow, currentCol)) {
inversions++;
}
}
}
if (tilesCopy.length % 2 != 0 && inversions % 2 != 0) return false;
if (tilesCopy.length % 2 == 0 && (inversions + this.zeroRow) % 2 == 0) return false;
return true;
}
#Override
public boolean equals(Object y) {
if (!(y instanceof Board)) return false;
Board that = (Board) y;
// why bother checking whole array, if last elements aren't equals
return this.tileAt(N - 1, N - 1) == that.tileAt(N - 1, N - 1) && this.size() == that.size() && Arrays.deepEquals(this.tilesCopy, that.tilesCopy);
}
#Override
public int hashCode() {
if (this.hashCode != -1) return hashCode;
// more optimized version(Arrays.hashCode is too slow)?
this.hashCode = Arrays.deepHashCode(tilesCopy);
return this.hashCode;
}
public Collection<Board> neighbors() {
if (neighbors != null) return neighbors;
if (this.zeroRow == -1 && this.zeroCol == -1) findZeroTile();
neighbors = new HashSet<>();
if (zeroRow - 1 >= 0) generateNeighbor(zeroRow - 1, true);
if (zeroCol - 1 >= 0) generateNeighbor(zeroCol - 1, false);
if (zeroRow + 1 < this.size()) generateNeighbor(zeroRow + 1, true);
if (zeroCol + 1 < this.size()) generateNeighbor(zeroCol + 1, false);
return neighbors;
}
private void findZeroTile() {
outerloop:
for (int i = 0; i < this.size(); i++) {
for (int j = 0; j < this.size(); j++) {
if (tileAt(i, j) == 0) {
this.zeroRow = i; // index starting from 0
this.zeroCol = j;
break outerloop;
}
}
}
}
private void generateNeighbor(int toPosition, boolean isRow) {
int[][] copy = Arrays.copyOf(this.tilesCopy, tilesCopy.length);
if (isRow) swapEntries(copy, zeroRow, zeroCol, toPosition, zeroCol);
else swapEntries(copy, zeroRow, zeroCol, zeroRow, toPosition);
neighbors.add(new Board(copy));
}
private void swapEntries(int[][] array, int fromRow, int fromCol, int toRow, int toCol) {
int i = array[fromRow][fromCol];
array[fromRow][fromCol] = array[toRow][toCol];
array[toRow][toCol] = i;
}
public String toString() {
StringBuilder s = new StringBuilder(4 * N * N); // optimization?
// s.append(N + "\n");
for (int i = 0; i < N; i++) {
for (int j = 0; j < N; j++) {
s.append(String.format("%2d ", tileAt(i, j)));
}
s.append("\n");
}
return s.toString();
}
private void checkRep() {
assert tilesCopy.length > 0;
}
}
The problem you have is at line
int[][] copy = Arrays.copyOf(this.tilesCopy, tilesCopy.length);
You assume here to have copied the matrix. But actually you've copied the array with references to arrays in the 2nd dimension.
In other words
copy == this.tolesCopy // false
copy[0] == this.tilesCopy[0] // true
copy[1] == this.tilesCopy[1] // true
copy[2] == this.tilesCopy[2] // true
what leads to have the same matrix changed multiple times, and even to an invalid/unsolvable state.
The easiest fix I see in your code would be to change the generateNeighbor method
private void generateNeighbor(int toPosition, boolean isRow) {
Board board = new Board(this.tilesCopy);
if (isRow) swapEntries(board.tilesCopy, zeroRow, zeroCol, toPosition, zeroCol);
else swapEntries(board.tilesCopy, zeroRow, zeroCol, zeroRow, toPosition);
neighbors.add(board);
}
Although the overal idea looks good. There are multiple other things that can be improved. I suggest you to have a look at this implementation
I am making a Sudoku game in Java and I need some help.
I've got two classes for generating the Sudoku puzzle: SudokuSolver, SudokuGenerator`.
The SudokuSolver creates a full valid Sudoku puzzle for an empty table and the SudokuGenerator removes a random value from the table and then checks (using SudokuSolver) if the Sudoku puzzle is unique.
I found out that the Sudoku puzzle isn't unique, so I think my algorithm for checking the uniqueness of the Sudoku puzzle is bad.
For example, I have this Sudoku puzzle
497816532
132000000
000000000
910600080
086009000
000084963
021063059
743050020
600278304
And this solution:
497816532
132**745**698
568392471
914**637**285
386529147
275184963
821463759
743951826
659278314
I went to https://www.sudoku-solutions.com/ and I added the pattern of my Sudoku and they gave me another solution:
497816532
132**547**698
568392471
914**635**287
386729145
275184963
821463759
743951826
659278314
The funny think is that they're saying that This puzzle is valid and has a unique solution.
Some opinions?
SudokuSolver
public class SudokuSolver {
public static final int GRID_SIZE = 9;
public static final int SUBGRID_SIZE = 3;
private static int validRow = 0;
private static int validCol = 0;
private int[] nums = {1, 2, 3, 4, 5, 6, 7, 8, 9};
public boolean solveSudoku(int[][] values, int forbiddenNum) {
if(!findUnassignedLocation(values)) return true;
//suffle the nums array - for having a different valid sudoku
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(num == forbiddenNum) continue; //
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(solveSudoku(values, forbiddenNum)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
public boolean createValidSudoku(int[][] values) {
if(!findUnassignedLocation(values)) return true;
shuffleNums();
for (int i = 0; i < GRID_SIZE; i++) {
int num = nums[i];
if(isSafe(values,validRow, validCol, num)) {
values[validRow][validCol] = num;
if(createValidSudoku(values)) return true;
if(validCol == 0) {
validRow--;
validCol = 8;
}else{
validCol--;
}
values[validRow][validCol] = 0;
}
}
return false;
}
private void shuffleNums() {
Random random = new Random();
for(int i = nums.length - 1; i > 0; i--) {
int index = random.nextInt(i + 1);
int a = nums[index];
nums[index] = nums[i];
nums[i] = a;
}
}
private boolean findUnassignedLocation(int[][] values) {
for(int row = 0; row < GRID_SIZE; row++) {
for(int col = 0; col < GRID_SIZE; col++) {
if (values[row][col] == 0) {
validRow = row;
validCol = col;
return true;
}
}
}
return false;
}
private boolean usedInRow(int[][] values, int row, int num) {
for (int col = 0; col < GRID_SIZE; col++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInCol(int[][] values, int col, int num) {
for (int row = 0; row < GRID_SIZE; row++) {
if(values[row][col] == num) return true;
}
return false;
}
private boolean usedInBox(int[][] values, int boxStartRow, int boxStartCol, int num) {
for(int row = 0; row < SUBGRID_SIZE; row++) {
for (int col = 0; col < SUBGRID_SIZE; col++) {
if (values[row + boxStartRow][col + boxStartCol] == num) return true;
}
}
return false;
}
private boolean isSafe(int[][] values,int row, int col, int num) {
return !usedInRow(values, row, num) &&
!usedInCol(values, col, num) &&
!usedInBox(values, row - row % 3, col - col % 3, num);
}
public void printGrid(int[][] values) {
for (int row = 0; row < GRID_SIZE; row++) {
for (int col = 0; col < GRID_SIZE; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
}
SudokuGenerator
public class SudokuGenerator {
private int[][] generatorValues = new int[9][9];
public void generateSudoku() {
SudokuSolver sudokuSolver = new SudokuSolver();
//generate a random valid sudoku for an empty table
sudokuSolver.createValidSudoku(generatorValues);
int count = 0;
printNums(generatorValues);
while(count < 40){
Random random = new Random();
int row = 0;
int col = 0;
if(count < 15){
row = random.nextInt(3);
col = random.nextInt(9);
} else if (count >= 15 && count < 30) {
row = random.nextInt(3) + 3;
col = random.nextInt(9);
}else {
row = random.nextInt(3) + 6;
col = random.nextInt(9);
}
int num = generatorValues[row][col];
int tempValues[][] = Arrays.copyOf(generatorValues, generatorValues.length);
//System.out.println("Row:" + row + "Col: " + col + "Num: " + num);
//Set the cell to 0;
if(generatorValues[row][col] != 0){
generatorValues[row][col] = 0;
} else{
continue;
}
//If found a solution, set cell back to original num
if(sudokuSolver.solveSudoku(tempValues, num)) {
generatorValues[row][col] = num;
continue;
}
count++;
}
System.out.println("------------------");
printNums(generatorValues);
}
private void printNums(int[][] values) {
for (int row = 0; row < 9; row++) {
for(int col = 0; col < 9; col++) {
System.out.print(values[row][col]);
}
System.out.println();
}
}
public int[][] getGeneratorValues () {
return generatorValues;
}
}
I need to have each cell in the firstArray become the sum of all adjacent cells then dump that answer into secondArray.
Example:
Initial array with random numbers:
3 5 11
5 9 14
1 2 8
Computed array:
19 42 41
20 49 48
33 62 44
3 spot([0][0]) is 5 + 9 + 5 = 19, and so on. Here's what I have:
public class ProcessArray {
private int rows;
private int columns;
private int [][] firstArray;
private int [][] secondArray;
public ProcessArray(int rows, int columns) {
this.rows=rows;
this.columns=columns;
firstArray = new int[rows][columns];
secondArray = new int[rows][columns];
initializeArray(firstArray, secondArray);
randomlyFillArray(firstArray);
System.out.println("Initial array with random numbers: ");
printArray(firstArray, secondArray, rows, columns);
getFirstArray(firstArray);
System.out.println("Computed array:");
computeArrayValues(firstArray);
}
private void initializeArray(int firstArray[][], int secondArray[][]){
for(int i = 0; i <firstArray.length; i++){
for (int j =0; j<firstArray[i].length; j++){
firstArray[i][j] = (0);
}
}
for(int i = 0; i <secondArray.length; i++){
for (int j =0; j<secondArray[i].length; j++){
secondArray[i][j] = (0);
}
}
}
public void randomlyFillArray(int firstArray[][]){
for(int i = 0; i <firstArray.length; i++){
for (int j =0; j<firstArray[i].length; j++){
firstArray[i][j] = (int)(Math.random()*15);
}
}
}
//here's where I try to have it add, I don't know what loop to have it run to go to each spot in the `firstArray`:
public void computeArrayValues(int firstArray[][]){
int x=1;
int y=1;
int sum;
int topLeft = firstArray[x-1][y-1];
int top = firstArray[x][y-1];
int topRight = firstArray[x+1][y-1];
int midLeft = firstArray[x-1][y];
int midRight = firstArray[x+1][y];
int botLeft = firstArray[x-1][y+1];
int bot = firstArray[x][y+1];
int botRight = firstArray[x+1][y+1];
secondArray[0][0]= (bot+botRight+midRight);
for (x=0; x<firstArray.length; x++){
for(y=0; y<firstArray.length; y++){
secondArray[x][y] = (topLeft+top+topRight+midLeft+midRight+botLeft+bot+botRight);
}
}
System.out.println(secondArray[x][y]);
}
public void printArray(int firstArray[][], int secondArray[][], int rows, int columns){
for (int i = 0; i < rows; i++){
for (int j = 0; j < columns; j++){
System.out.printf(String.format("%4s", firstArray[i][j]));
}
System.out.println();
}
}
public int[][] getFirstArray(int array[][]){
array = firstArray;
return array;
}
public int[][] getSecondArray(int array[][]){
array = secondArray;
return array;
}
}
Presuming you are looking for suggestions on alternative approaches, I would suggest encapsulating cell coordinates and using streams of cells instead of iteration. This assumes java 8 (naturally):
class Cell {
private final int row;
private final int col;
private Cell(int row, int col) {
this.row = row;
this.col = col;
}
public static Stream<Cell> streamCells(int rows, int cols) {
return IntStream.range(0, rows)
.flatMap(row -> IntStream.range(0, cols)
.flatMap(col -> new Cell(row, col)));
}
public Stream<Cell> streamAdjacentCells(int rows, int cols) {
return IntStream.range(row - 1, row + 1)
.flatMap(row -> IntStream.range(col - 1, col + 1)
.flatMap(col -> new Cell(row, col)))
.filter(cell -> cell.row >= 0 && cell.col >= 0)
.filter(cell -> cell.row < rows && cell.col < cols)
.filter(cell -> cell.row != this.row && cell.col != this.col);
}
public int getValue(int[][] array) {
return array[row][col];
}
public void setValue(int[][] array, int value) {
array[row][col] = value;
}
}
Then the code to set adjacent values quite simple:
int[][] destination = new int[rows][cols];
Cell.streamCells(rows, cols)
.forEach(cell -> setValue(
destination,
cell.streamAdjacentCells(rows, cols)
.mapToInt(adj -> getValue(source, adj))
.sum()));
This will fulfill the stated requirement, but running the program with the example data will output:
19 42 28
20 49 35
16 37 25
That would be the correct output for a sum of all adjacent cells (let me know if I misunderstood the question).
public class ArraySum {
static int[][] sum(int array[][]) {
// Asuming square arrays
int size = array.length;
int result[][] = new int[size][size];
// For every cell in the table
for (int i = 0; i < size; i++) {
for (int j = 0; j < size; j++) {
// Iterate the neighbors
for (int n = -1; n <= 1; n++) {
for (int m = -1; m <= 1; m++) {
// Discard the cell
if (n == 0 && m == 0) {
continue;
}
int ii = i - n;
int jj = j - m;
// Check if the neighbor coordinates are
// inside of the array bounds
if (ii >= 0 && ii < size && jj >= 0 && jj < size) {
result[i][j] += array[ii][jj];
}
}
}
}
}
return result;
}
public static void main(String... args) {
int a[][] = { {3, 5, 11},
{5, 9, 14},
{1, 2, 8} };
int r[][] = sum(a);
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
System.out.printf("%d ", r[i][j]);
}
System.out.println();
}
}
}