public class matrix {
public static void main (String[] args) {
int[][] matrix = Array();
}
}
You need a count for each row for all columns and vice versa.
As you count upto 1 a boolean suffices: having found a non-zero element.
Instead of for row/for col and for col/for row which is a non space consuming fine algorith you could have done:
public static boolean isGPM(int [][] matrix) {
boolean[] rowNonZero = new boolean[matrix.length];
boolean[] colNonZero = new boolean[matrix[0].length];
for (int row = 0; row < matrix.length; row++) {
for (int col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] != 0) {
if (rowNonZero[row] || colNonZero[col]) {
return false;
}
rowNonZero[row] = true;
colNonZero[col] = true;
}
}
}
return true;
}
Above an array for rowNonZero is not needed as you see.
Your version would be:
public static boolean isGPM(int [][] matrix) {
for (int row = 0; row < matrix.length; row++) {
boolean nonZero = false;
for (int col = 0; col < matrix[0].length; col++) {
if (matrix[row][col] != 0) {
if (nonZero) {
return false;
}
nonZero = true;
}
}
}
for (int col = 0; col < matrix[0].length; col++) {
boolean nonZero = false;
for (int row = 0; row < matrix.length; row++) {
if (matrix[row][col] != 0) {
if (nonZero) {
return false;
}
nonZero = true;
}
}
}
return true;
}
Since my reputation is too low to comment I'll post an answer. In isGPM function in your loops when you check if count/sum is not equal to 1, in your first iteration it is always going to be 0 and return false, unless there is a number that is different from 0 on the first position in array.
The way I'd dodge this is to do it like this:
int count = 0;
for(int row = 0; row < matrix.length; row++) {
for(int col = 0; col < matrix[0].length; col++)
if (matrix[row][col] != 0) {
count++;
}
}
if (count != 1)
return false;
You just move out the variable declaration of count from for loop and after the loop is finished you do the check. You can do the same thing for your other loop in the function.
Related
i have to check the validity of a sudoku as a homework. the rows and cols were no big deal, but i'm stuck at checking the boxes.
i want to loop through the 3x3 sub-boxes and check them for duplicates, with copying the numbers into a smaller 3x3 array, flattening it and then checking it for duplicates.
my while loop doesn't seem to make sense tho, the first iteration works but the second one writes wrong values into my new array. i just don't know where to add my boxcount.
i feel like a noob, if someone can help i'd be thankful
private static boolean isValidSudokuSolution(int[][] sudokuField) {
// TODO: Implementieren Sie hier Ihre Lösung für die Methode
//rows
int row = 0;
while (row < sudokuField.length) {
for (int i = 0; i < sudokuField[row].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[row][i] == sudokuField[row][j]) {
return false;
}
}
}
row++;
}
//cols
int col = 0;
while (col < sudokuField.length) {
for (int i = 0; i < sudokuField[col].length; i++) {
for (int j = 0; j < i; j++) {
if (sudokuField[i][col] == sudokuField[j][col]) {
return false;
}
}
}
col++;
}
//box
int boxCount = 0;
while (boxCount < sudokuField.length) {
//create box array
int[][] box = new int[3][3];
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
box[i][j] = sudokuField[i + boxCount][j];
}
}
//flatten box
int[] flattenedBox = new int[sSize];
int counter = 0;
for (int i = 0; i < box.length; i++) {
for (int j = 0; j < box[i].length; j++) {
int num = box[i][j];
flattenedBox[counter + j] = num;
}
counter += 3;
}
//look for duplicates
for (int i = 0; i < flattenedBox.length; i++) {
for (int j = 0; j < i; j++) {
if (flattenedBox[i] == flattenedBox[j]) {
return false;
}
}
}
boxCount += 3;
}
return true;
}
I'm new to coding in Java. I need to compute the average number of blocks per column on a board. The below is to count the total number of blocks within all columns on a board and then divides by the number of columns.
this is what I have so far but I think it's not right. i feel like I'm missing something.
public int getAverageColumnBlocks(Board board)
{
int avgColumnBlock = 0;
for (int col = 0; col < Board.WIDTH; col++)
{
for (int row = 0; row < Board.HEIGHT; row++)
{
if(board.isBlockAt(col, row))
{
avgColumnBlock++;
}
}
}
return avgColumnBlock;
}
public int getAverageColumnBlocks(Board board)
{
int total = 0;
for (int col = 0; col < Board.WIDTH; col++)
{
for (int row = 0; row < Board.HEIGHT; row++)
{
if(board.isBlockAt(col, row))
{
total++;
}
}
}
return total/Board.WIDTH;
}
The following pice of code is my code for my Game of Life. For some reason it works very strangely. The first few steps of the game are wrong, and then the whole output turns to zeroes. I don't know which method is causing the problem, but I assume it is the count neighbors method.
The board is a 2D array called GOLBoard, and the x and y coordinates are cellRow and cellCol. Alive cells are 1, and dead cells are 0s. The way I avoid out of bounds problems are by making the board 12x12, but I use only 1 to 11 for rows and columns.
<code> #Override
public int countNeighbours(int cellRow, int cellCol) {
int neighbours = 0;
for (int i = cellRow-1; i < cellRow + 2; i++) {
for (int j = cellCol - 1; j < cellCol + 2; j++) {
if (GOLBoard[i][j] == 1) {
neighbours += 1;
}
}
}
if (GOLBoard[cellRow][cellCol] == 1) {
return(neighbours-1);
} else {
return(neighbours);
}
}
#Override
public int applyRules(int cellRow, int cellCol) {
int alive = 0;
if (GOLBoard[cellRow][cellCol] == 1) {
if (countNeighbours(cellRow, cellCol) == 2 || countNeighbours(cellRow, cellCol) == 3) {
alive = 1;
} else if (countNeighbours(cellRow, cellCol) < 2 || countNeighbours(cellRow, cellCol) > 3) {
alive = 0;
}
}
if (GOLBoard[cellRow][cellCol] == 0) {
if (countNeighbours(cellRow, cellCol) == 3) {
alive = 1;
}
}
return (alive);
}
#Override
public void takeStep() {
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
GOLBoard[row][col] = applyRules(row, col);
}
}
}
#Override
public String toString() {
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
System.out.print("[" + GOLBoard[row][col] + "]");
}
System.out.println("");
}
return("");
}
} <code>
If I am recalling the rules of GOL correctly, the evolution of the board should proceed in a series of "generations", wherein the state of each cell on a "new" board is determined solely by the conditions of the corresponding cell on the "old" board. Your program is trying to continuously evolve a single board, so that changes to previously computed cells are affecting the outcome of cells yet to be computed. Your takeStep routine should be doing something more like this:
newBoard = new int[12][12];
for (int row = 1; row < 11; row++) {
for (int col = 1; col < 11; col++) {
newBoard[row][col] = applyRules(row, col);
}
}
GOLBoard = newBoard;
As far as I can tell, your countNeighbours is OK.
I was wondering if you guys could help me out with some of my code. I have been programming this puzzle creator, but when I attempt to generate values for my two-dimensional array, I get an OutOfBoundsException. I'm sure this solution is simple, but for whatever reason, I can't seem to find what's wrong. (Also, of course, there is a driver class that goes along with this, but I don't think that's necessary to include here.)
import java.util.*;
public class ThirtyWonderful
{
private int dimen;
public ThirtyWonderful (int dimensions)
{
dimen = dimensions;
}
public ThirtyWonderful()
{
dimen = 5;
}
Random gen = new Random();
int[][] nums = new int [dimen][dimen];
public void genPuzzle()
{
for (int count = 0; count < dimen; count++)
{
for(int col = 0; col < dimen; col++)
{
nums[count][col] = gen.nextInt(9) + 1;
}
}
checkAcc();
if(checkAcc() == true)
{
for (int count = 0; count < dimen; count++)
{
for(int col = 0; col < dimen; col++)
{
System.out.print(nums[count][col] + " ");
}
System.out.println();
}
}
}
public boolean checkAcc()
{
int tot = 0;
for (int count = 0; count < dimen; count++)
{
for(int col = 0; col < dimen; col++)
{
tot += nums[count][col];
}
if(tot != 31)
return false;
}
for (int count = 0; count < dimen; count++)
{
for(int col = 0; col < dimen; col++)
{
tot += nums[count][col];
}
if(tot != 31)
return false;
}
return true;
}
}
You are declaring nums with new int [dimen][dimen]; Before dimen even initialization, By default dimen value is 0, so nums is initialize with new int[0][0]
Here is the Fix Code
public class ThirtyWonderful {
private int dimen;
Random gen = new Random();
int[][] nums;
public ThirtyWonderful(int dimensions) {
this.dimen = dimensions;
nums = new int[dimen][dimen];
}
public ThirtyWonderful() {
this(5);
}
public void genPuzzle() {
for (int count = 0; count < dimen; count++) {
for (int col = 0; col < dimen; col++) {
nums[count][col] = gen.nextInt(9) + 1;
}
}
checkAcc();
if (checkAcc() == true) {
for (int count = 0; count < dimen; count++) {
for (int col = 0; col < dimen; col++) {
System.out.print(nums[count][col] + " ");
}
System.out.println();
}
}
}
public boolean checkAcc() {
int tot = 0;
for (int count = 0; count < dimen; count++) {
for (int col = 0; col < dimen; col++) {
tot += nums[count][col];
}
if (tot != 31) {
return false;
}
}
for (int count = 0; count < dimen; count++) {
for (int col = 0; col < dimen; col++) {
tot += nums[count][col];
}
if (tot != 31) {
return false;
}
}
return true;
}
}
you should initialize your array object in your constructors. you are initializing your array at class load time before your object is instantiated.
My code for filling sudoku board looks like this:
public class SudokuBoard {
static int N = 9;
static int[][] grid = new int[N][N];
static void printGrid()
{
for (int row = 0; row < N; row++)
{
for (int col = 0; col < N; col++) {
System.out.printf("%5d", grid[row][col]);
}
System.out.println("\n");
}
}
private static boolean checkRow(int row, int num)
{
for( int col = 0; col < 9; col++ )
if(grid[row][col] == num)
return false;
return true;
}
private static boolean checkCol(int col, int num)
{
for( int row = 0; row < 9; row++ )
if(grid[row][col] == num)
return false;
return true;
}
private static boolean checkBox(int row, int col, int num)
{
row = (row / 3) * 3;
col = (col / 3) * 3;
for(int r = 0; r < 3; r++)
for(int c = 0; c < 3; c++)
if(grid[row+r][col+c] == num)
return false;
return true;
}
public static boolean fillBoard(int row, int col, int[][] grid)
{
if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}
if(grid[row][col] != 0)
return fillBoard(row+1, col, grid);
for(int num = 1; num <=9; num++)
{
if(checkRow(row,num) && checkCol(col,num) && checkBox(row,col,num)){
grid[row][col] = num;
if(fillBoard(row+1, col, grid))
return true;
}
}
grid[row][col] = 0;
return false;
}
static public void main(String[] args){
fillBoard(0, 0, grid);
printGrid();
}
}
It uses backtrack algorithm to check if placement of numbers are good according to sudoku game puzzle rules.
It throws errors:
Exception in thread "main" java.lang.ArrayIndexOutOfBoundsException: 9
at SudokuBoard.fillBoard(SudokuBoard.java:68)
at SudokuBoard.fillBoard(SudokuBoard.java:74) x9
at SudokuBoard.main(SudokuBoard.java:84)
Where is it out of bounds? I cannot see that...
This block looks wrong:
if(row==9)
{
col = 0;
if(col++ == 9)
return true;
}
I suspect you want this:
if(row==9) {
row = 0;
if(++col == 9)
return true;
}
col++ increments col, but returns the old value. You probably meant to use ++col, which returns the new value. (see Java: Prefix/postfix of increment/decrement operators?)
In your code, when fillBoard(8, 8, grid) is called, col is increased to 9, but (col++ == 9) gets evaluated to false, because col++ returns 8. So you then try to access grid[8][9], which is when the exception is thrown.