Cannot convert from int to boolean - java

private static boolean allNinePresent(int[][] array){
int total = 0;
for (int row = 0; **array.length**; row++){
for (int col = 0; **array[row].length**; col++){
int addEach = array[row][col];
total = addEach + total;
}
}
if (total == 45){
return true;
} else {
return false;
}
}
Shouldn't the array be an int? Why is it converting it from an int to boolean? How can I fix this.

As pointed in official tutorial for statement looks like
for (initialization; termination; increment) {
statement(s)
}
and
When the termination expression evaluates to false, the loop terminates.
In your case *array.length is used in place of termination, but in Java booleans can't be represented by integers, so something like if(1) is not valid. This means that you need to be more specific and use actual expression which can be evaluated to boolean (true or false), like
true
false
a<b
a>=b
That is why your loops should look more like
for (int row = 0; row<array.length; row++){
for (int col = 0; cor<array[row].length; col++){
BTW
if (total == 45){
return true;
} else {
return false;
}
can be rewritten to something simpler like
return total == 45;

for (int col = 0; array[row].length; col++){
second part accepts a boolean expression,
; array[row].length;
you are passing int
you need
row < array.length
and
col < array[row].length

The second part of the for loop isn't the stopping value, it's the condition under which the loop will continue looping. Use row < array.length and col < array[row].length.

Related

How to traverse through 2d array and count how many elements are greater than 1 in each row in row major order

I'm writing a method that traverses through a 2d array in row-major order and at the start of each row, I initialize a count variable to zero. In the inner loop, if a value is non-zero I increment the count variable. At the end of the row, if the count variable is not exactly equal to 1, return false. Ive been working on this for about 2 weeks and can't find my error. Please point me in the right direction.
** Don't mind the print statements I'm trying to see how much the count is and my code only seems to hit the second row of the array
public static boolean isGPM(int[][] matrix) {
int count =0;
for (int row = 0; row < matrix.length; row++) {
count =0;
for (int col = 0; col < matrix[row].length; col++) {
if (matrix[row][col] > 0) {
count++;
}
else {
return !gpm;
}
}
}
System.out.println(count);
return gpm;
}
If I understand you correctly, you only care about the per-row count. This should work:
int count = 0;
// Process each row...
for (int row = 0; row < matrix.length; row++) {
count = 0;
// Process each column...
for (int col = 0; col < matrix[row].length; col++) {
// Check the cell.
if (matrix[row][col] != 0) {
count++;
}
}
// Row processing complete. Check count.
if (count != 1) {
System.out.println(count);
return gpm;
}
}

Java 2D array diagonals

I wrote a program to try to solve the 8 queens problem and one part of it required me to test all of the forward and backward diagonals to make sure there were no conflicts. I got the backwards to work perfectly but this part of the forward one was returning true while I was testing and I really can't figure out why. And help would be greatly appreciated :)
class NonAttackingQueen {
static char [][] board = { {'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'},
{'X','Q','X','X','X','X','X','X'},
{'Q','X','X','X','X','X','X','X'},
{'X','X','X','X','X','X','X','X'} };
public static boolean diagonalsClear () {
int numQueens;
boolean clear = true;
for (int numSpots = 1; numSpots < 9; numSpots++) {
numQueens = 0;
for (int row = 0; row < numSpots - 1; row++) {
if (board[row][numSpots - 1 - row] == 'Q')
numQueens++;
}
if (numQueens > 1) {
clear = false;
break;
}
}
for (int numSpots = 7; numSpots > 0; numSpots--) {
numQueens = 0;
for (int row = 7; row > 7 - numSpots; row--) {
if (board[row][15-row-numSpots] == 'Q')
numQueens++;
}
if (numQueens > 1) {
clear = false;
break;
}
return clear;
}
}
Little trick to solve this problem. It is obvious, that you have mistake with matrix row and column indices calculation, and your loops do not cover all cells in it. Easiest way to check it, just print it out to console. I can see, that you have problem with for (int row = 0; row < numSpots - 1; row++). Firs iteration, when numSpots=1 it skips this loop. Correct is for (int row = 0; row <= numSpots - 1; row++).
Let me give you some notes about your example. I can see that two upper and lower part of the matrix you check with opposite direction, upper one you start with row=0 and lower one - col=0. I think to do the same calculation is much better for understanding. You could decomposite you task into three simple once:
Check one single diagonal, starting with given row and column;
check upper diagonals;
check lower diagonals.
I think example below is more clear for reading:
private static boolean isDiagonalClear(int row, int col) {
int total = 0;
do {
if (board[row--][col++] == 'Q')
total++;
} while (total <= 1 && row >= 0 && col < 8);
return total <= 1;
}
public static boolean diagonalsClear() {
for (int row = 0; row < 7; row++)
if (!isDiagonalClear(row, 0))
return false;
for (int col = 0; col < 8; col++)
if (!isDiagonalClear(7, col))
return false;
return true;
}

This is not printing anything i m expecting as '*' in 6 Row

package MyPackage;
public class StarPattern {
public static void main(final String[] args) {
int row;
int column = 0;
for (row = 0; row >= 6; row++) {
System.out.println(" * ");
}
}
}
You have misunderstood the for statement declaration:
for (row = 0; row >= 6; row++) {
Formally, the row >= 6 is called the Expression. This is evaluated before the loop body (formally, the "Statement") is executed:
If it is evaluated to true, the loop body is executed; then the row++ is evaluated (the ForUpdate); then the iteration happens again.
If it evaluates to false, the loop body is not executed, and execution moves on to execute the next statement after the loop.
If row = 0, then row >= 6 is immediately false, so the loop body never executes.
I think you have perhaps assumed the other way round: that the loop stops once the Expression evaluates to true, but keeps going if it is false. I don't think there is a particular reason why it couldn't work this way; but this just isn't the way that loop semantics in Java (and many other languages) are defined.
So, simply invert the expression:
for (row = 0; row < 6; row++) {
// ^ Here
It should be like this
int row;
int column = 0;
for (row = 0; row < 6; row++) {
System.out.println(" * ");
}
You want to do the System.out every iteration that row is less than 6.
for (row = 0; row < 6; row++) {
System.out.println(" * ");
}

Solve sudoku by backtracking (java)

public static int[][] solve(int[][] input){
for (int i = 0; i < 9*9; i++){
if(input[i / 9][i % 9] != 0){
continue;
}
for (int j = 1; j <= 9; j++){
if(validNumber(input, i / 9, i % 9, j)){
input[i / 9][i % 9] = j;
solve(input);
}
}
}
return input;
}
This method should solve a (solvable) sudoku puzzle via backtracking regardless of the initial situation. It works like this:
Given a sudoku puzzle it iterates from the upper left corner over each row to the lower right corner of the 2D array. When there is already a number, it gets skipped. When there is a zero (empty field) it calculates possible values via the validNumber method. The first valid number (from 1 to 9) is put in the field and the method goes to the next field.
In this algorithm the method does not now whether or not a valid number will eventually render the puzzle unsolvable.
I want to alter it like this:
At the end, when the method finishes iterating through the whole 2d array, every entry of the array gets tested if it is a zero or not.
If there is even one zero the whole algorithm must go to the place where the very first "valid" number was put in. Now, the next "valid" number is put in and so on until there are no zeroes at the end of the algorithm.
I have some troubles implementing this thought. It seems to me there must be an other for loop somewhere, or something like a goto statement, but I don't know where to put it.
Any advice?
I implemented a Sudoku solver once before. It was a bit more complicated than what you had, but solved the game in a blink. :)
What you are attempting to do is solve Sudoku by "Brute Force" and using (tail) recursion. That means you are attempting to solve the board by iterating over all 981 possible combinations. 9 to the power of 81 is... well it's a big number. And so your approach will take eternity, but you'll run out of stack space from the tail recursion much sooner.
When I implemented Sudoko, it was more straight up. It kept a 9x9 array of "items", where each item was the value in the square, and an array of 9 booleans representing candidates (true == viable, false == eliminated). And then it just did a non-recursive loop of solving the board.
The main loop would start with the simple process of finding squares with only 1 remaining candidate. Then the next step would do simple candidate elimination based on values already assigned. Then it would work its way into more complicated elimination techniques such as X-Wing.
Your algorithm does not actually backtrack. It moves forward if it can, but it never moves backwards when it realizes it's stuck in a corner. This is because it never returns any knowledge up the stack, and it never resets squares. Unless you get really lucky, your code will get the game board into a cornered state, and then print out that cornered state. To backtrack, you need to reset the last square you set (the one that got you cornered) to zero, so your algorithm will know to keep trying other things.
For understanding backtracking, I highly recommend a book called The Algorithm Design Manual by Steven Skiena. I read it when I was preparing for SWE interviews, and it really improved my knowledge of backtracking, complexity, and graph search. The second half of the book is a catalog of 75 classic algorithmic problems, and Sudoku is one of them! He has an interesting analysis of optimizations you can make to prune the search tree and solve very hard puzzle boards. Below is some code I wrote a long time ago after reading this chapter (probably not that high quality by my current standards, but it works). I just read through it really quickly and added the solveSmart boolean in the solve method which allows you to turn one of those optimizations on or off, which results in a pretty big time savings when solving a "hard" class Sudoku board (one with only 17 squares filled in to start with).
public class Sudoku {
static class RowCol {
int row;
int col;
RowCol(int r, int c) {
row = r;
col = c;
}
}
static int numSquaresFilled;
static int[][] board = new int[9][9];
static void printBoard() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
System.out.print(" " + (board[i][j] == 0 ? " " : board[i][j]) + " ");
if (j % 3 == 2 && j < 8)
System.out.print("|");
}
System.out.println();
if (i % 3 == 2 && i < 8)
System.out.println("---------|---------|---------");
}
System.out.println();
}
static boolean isEntireBoardValid() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (!isBoardValid(i, j)) {
return false;
}
}
}
return true;
}
static boolean isRowValid(int row) {
int[] count = new int[9];
for (int col = 0; col < 9; col++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}
static boolean isColValid(int col) {
int[] count = new int[9];
for (int row = 0; row < 9; row++) {
int n = board[row][col] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
return true;
}
static boolean isSquareValid(int row, int col) {
int r = (row / 3) * 3;
int c = (col / 3) * 3;
int[] count = new int[9];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int n = board[r + i][c + j] - 1;
if (n == -1)
continue;
count[n]++;
if (count[n] > 1)
return false;
}
}
return true;
}
static boolean isBoardValid(int row, int col) {
return (isRowValid(row) && isColValid(col) && isSquareValid(row, col));
}
static RowCol getOpenSpaceFirstFound() {
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
return new RowCol(i, j);
}
}
}
return new RowCol(0, 0);
}
static RowCol getOpenSpaceMostConstrained() {
int r = 0, c = 0, max = 0;
int[] rowCounts = new int[9];
int[] colCounts = new int[9];
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] != 0)
rowCounts[i]++;
if (board[j][i] != 0)
colCounts[i]++;
}
}
int[][] squareCounts = new int[3][3];
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3; j++) {
int count = 0;
for (int m = 0; m < 3; m++) {
for (int n = 0; n < 3; n++) {
if (board[(i * 3) + m][(j * 3) + n] != 0)
count++;
}
}
squareCounts[i][j] = count;
}
}
for (int i = 0; i < 9; i++) {
for (int j = 0; j < 9; j++) {
if (board[i][j] == 0) {
if (rowCounts[i] > max) {
max = rowCounts[i];
r = i;
c = j;
}
if (colCounts[j] > max) {
max = rowCounts[j];
r = i;
c = j;
}
}
}
}
return new RowCol(r, c);
}
static boolean solve() {
if (81 == numSquaresFilled) {
return true;
}
boolean solveSmart = true;
RowCol rc = solveSmart ? getOpenSpaceMostConstrained() : getOpenSpaceFirstFound();
int r = rc.row;
int c = rc.col;
for (int i = 1; i <= 9; i++) {
numSquaresFilled++;
board[r][c] = i;
if (isBoardValid(r, c)) {
if (solve()) {
return true;
}
}
board[r][c] = 0;
numSquaresFilled--;
}
return false;
}
public static void main(String[] args) {
// initialize board to a HARD puzzle
board[0][7] = 1;
board[0][8] = 2;
board[1][4] = 3;
board[1][5] = 5;
board[2][3] = 6;
board[2][7] = 7;
board[3][0] = 7;
board[3][6] = 3;
board[4][3] = 4;
board[4][6] = 8;
board[5][0] = 1;
board[6][3] = 1;
board[6][4] = 2;
board[7][1] = 8;
board[7][7] = 4;
board[8][1] = 5;
board[8][6] = 6;
numSquaresFilled = 17;
printBoard();
long start = System.currentTimeMillis();
solve();
long end = System.currentTimeMillis();
System.out.println("Solving took " + (end - start) + "ms.\n");
printBoard();
}
}
Eventually validNumber() method will not return any number because there is no possibilities left that means one of the previous choices was incorrect. Just imagine that the algorithm is started with the empty grid (obviously this puzzle is solvable1).
The solution is to keep tree of possible choices and if some choices are incorrect, then just remove them from the tree and use the next available choice (or step back on a higher level of the tree, if there is no choice left in this branch). This method should find a solution if any. (Actually this is how I implemented my sudoku solver some time ago.)
1 IMHO there are 3 different kinds of sudoku:
"true" correct sudoku that has a single unique complete solution;
ambiguous sudoku that has multiple distinct complete solutions, e.g. a puzzle with only 7 different numbers, so it has at least two distinct solutions that differ by swapping 8th and 9th numbers;
incorrect sudoku that has no complete solution, e.g. with a row with two or more occurrences of the same number.
With this definition, a solver algorithm should either:
prove that there is no solution;
return complete solution that satisfies the initial grid.
In the case of a "true" sudoku the result is a "true" solution by definition. In the case of an ambiguous sudoku the result can be different depending on the algorithm. An empty grid is the ultimate example of ambiguous sudoku.

Java 2d array, test for square

I'm given an array (a2d) and I need to determine if every row and column has the same number of elements as every other row and column. If it is then I set the Boolean isSquare to true.
I have come up with the following code, but it doesn't like it and it isn't giving me any suggestions on how to improve it.
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
if(a2d.length == a2d[row].length)
isSquare = true;
else
isSquare = false;
}
Am I testing this the wrong way or is there a better way?
There is no need for 2 loops you should be able to do something like this (I'm not going to give the code since it's homework)
1. Save the length of the array (a2d.length)
2. Loop over all the rows
3. Check to see if the given row has the same length
4. if Not return false
5. if you reach the end of the loop return true
for (int i = 0, l = a2d.length; i < l; i++) {
if (a2d[i].length != l) {
return false;
}
}
return true;
You just need to ensure that all of the lengths of the 2nd dimension arrays are the same length as the first dimension array.
if(a2d.length == a2d[row].length)
isSquare = true;
else
isSquare = false;
If the last element passes this will return true always. Try this:
isSquare = true;
for(int row = 0; row < a2d.length; row++){
for(int col = 0; col < a2d[row].length; col++)
if(a2d.length != a2d[row].length)
isSquare = false;
}
Save the length of the array (size.length)
Loop over all the rows
Check to see if the given row has the same length
Set isSquare if true go on otherwise false, to controll the loop
if you reach the end of the loop and isSquare
return true otherwise false
private static boolean isSquare(Object[][] matrix){
boolean isSquare = true;
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (int i = 0; i < size && isSquare; i++) {
isSquare = size == matrix[i].length;
}
return isSquare;
}
or not puristic with fori
private static boolean isSquare(Object[][] matrix){
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (int i = 0; i < size; i++) {
if(size != matrix[i].length)
return false;
}
return true;
}
with enhanced for
private static boolean isSquare(Object[][] matrix){
//Save the length of the array
int size = matrix.length;
//Loop over all the rows and Check to see if the given row has the same length
for (Object[] objects : matrix) {
if (size != objects.length)
return false;
}
return true;
}

Categories

Resources