Help Fix Java Two Dimensional Array Error. The code is supose to get a two dimen
ID: 3883474 • Letter: H
Question
Help Fix Java Two Dimensional Array Error.
The code is supose to get a two dimensional array of 9x9 ints, have a verification that it is a solution for a Sudoku puzzle, must return TRUE, and print out a line saying "It works!"
public class array
{
static int[][] grid = { {4, 2, 6, 5, 7, 1, 3, 9, 8},
{8, 5, 7, 2, 9, 3, 1, 4, 6},
{1, 3, 9, 4, 6, 8, 2, 7, 5},
{9, 7, 1, 3, 8, 5, 6, 2, 4},
{5, 4, 3, 7, 2, 6, 8, 1, 9},
{6, 8, 2, 1, 4, 9, 7, 5, 3},
{7, 9, 4, 6, 3, 2, 5, 8, 1},
{2, 6, 5, 8, 1, 4, 9, 3, 7},
{3, 1, 8, 9, 5, 7, 4, 6, 2} };
private boolean checkSudokuStatus(int[][] grid) {
for (int i = 0; i < 9; i++) {
int[] row = new int[9];
int[] square = new int[9];
int[] column = grid[i].clone();
for (int j = 0; j < 9; j ++)
{
row[j] = grid[j][i];
square[j] = grid[(i / 3) * 3 + j / 3][i * 3 % 9 + j % 3];
}
if (!(validate(column) && validate(row) && validate(square)))
return false;
}
return true;
for(return true)
{
System.out.println("Matrix works!");
}
if(return false)
{
System.out.println("Matrix doesnt work");
}
}
private boolean validate(int[] check)
{
int i = 0;
for (int number : check)
{
if (number != ++i)
return false;
}
return true;
}
}
Explanation / Answer
import java.util.Arrays;
/**
*
* @author Sam
*/
public class Sudoku {
private static boolean checkSudokuStatus(int[][] grid) {
for (int i = 0; i < 9; i++) {
int[] row = new int[9];
int[] square = new int[9];
int[] column = Arrays.copyOf(grid[i], 9);
int baseRow = (i/3) * 3;
int baseCol = (i%3) * 3;
for (int j = 0; j < 9; j ++)
{
row[j] = grid[j][i];
square[j] = grid[baseRow + j/3][baseCol + j%3];
}
if (!(validate(column) && validate(row) && validate(square)))
return false;
}
return true;
}
private static boolean validate(int[] check)
{
int i = 0;
Arrays.sort(check);
for (int number : check)
{
if (number != ++i)
return false;
}
return true;
}
public static void main(String[] args) {
int[][] matrix = new int[9][9];
//fill/get mtrix here
if (checkSudokuStatus(matrix))
System.out.println("Valid");
else
System.out.println("Not valid");
}
}
Here you go champ. I have included 2 methods and a main method for you. I hope they will help you. If you have any doubt please feel free to comment below. I shall be glad to help you till the problem gets resolved.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.