Two-Dimensional Loop OutOfBoundsException - Java - java

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.

Related

Save bidimensional Array

I am doing a Bingo program. I need to save the bingoCard (bidimensional array), because every time I execute a new move the card is different. And it need to be the same.
So I need to know how to save the card. I have a global variable (private static int[][]bingoCard=new int[3][9];) this is the code
public static int[][] bingoCard(){
int numRows = 3;
int numCols = 9;
int randomNumbersPerRow = 5;
int randomNumberBound = 90;
Random random = new Random();
bingoCard = new int[numRows][numCols];
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
bingoCard[row][col] = 0;
}
for (int i = 0; i < randomNumbersPerRow; i++) {
int indexToAssign = random.nextInt(numCols);
while (bingoCard[row][indexToAssign] != 0) {
indexToAssign = random.nextInt(numCols);
}
int numToAssign = random.nextInt(randomNumberBound)+1;
bingoCard[row][indexToAssign] = numToAssign;
}
}
for (int row = 0; row < numRows; row++) {
for (int col = 0; col < numCols; col++) {
System.out.printf("%2d ", bingoCard[row][col]);
}
System.out.println();
}
return bingoCard;
}

Sudoku check subboxes for duplicates

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;
}

Uses command line arguments to accept the desired number of rows and columns in java

it contains two java classes: TwoDMethods.java and TwoDTest.java
for TwoDMethods.java
The fill method fills the entire array with randomly-selected double values
between 0.0 and 100.0
The toString method returns a string representation of the two-dimensional
array, with the rows separated by "\n" and the columns vertically aligned
The sumColumns method returns a one-dimensional array containing the sum
of each column of the given two-dimensional array
The sumRows method returns a one-dimensional array containing the sum of
each row of the given two-dimensional array
The minValue method returns the smallest number in the given array
The maxValue method returns the largest number in the given array
I finished TwoDMethods.java but I am not sure how to write TwoDTest.java
and all methods should be static but the toString method always goes wrong when I add static.
For example, in TwoDTest.java using the following command:
java TwoDTest 3 4
the output will be:
toString() result:
41.23 72.99 8.60 38.62
70.32 52.00 38.63 90.60
72.98 6.54 94.50 91.34
Column sums:
184.53 131.54 141.73 220.56
Row sums:
161.45 251.55 265.36
Smallest number: 6.54
Largest number: 94.50
this is TwoDMethods.java:
public class TwoDMethods {
static int row, col;
static double sumRow, sumCol;
static double[][] array = new double[row][col];
public static void fill() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
array[i][j] = (double) (Math.random() * 100.00);
}
}
public String toString() {
String method2 ="";
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
method2 += String.format("%8.2f", array[row][col]) + " ";
}
method2 += "\n";
}
return method2;
}
public static double[] sumRows() {
double[] rowArray = new double[row];
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < col; j++) {
sumRow = sumRow + array[i][j];
}
rowArray[i] = sumRow;
}
return rowArray;
}
public static double[] sumColumns() {
double[] colArray = new double[col];
for (int i = 0; i < col; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + array[j][i];
}
colArray[i] = sumCol;
}
return colArray;
}
public static double minValue() {
double minValue = array[0][0];
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < array[j].length; i++) {
if (array[j][i] < minValue) {
minValue = array[j][i];
}
}
}
return minValue;
}
public static double maxValue() {
double maxValue = array[0][0];
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < array[j].length; i++) {
if (array[j][i] > maxValue) {
maxValue = array[j][i];
}
}
}
return maxValue;
}
}
I suggest not to make the methods static nor the members of class TwoDMethods. Here is my suggested code. It is basically your code with occurrences of static removed plus I added a constructor. The constructor initializes the class members. Note that you had an error in method toString in this line:
method2 += String.format("%8.2f", array[row][col]) + " ";
It should be:
method2 += String.format("%8.2f", array[i][j]) + " ";
I changed it in the below code.
public class TwoDMethods {
int row, col;
double sumRow, sumCol;
double[][] array = new double[row][col];
public TwoDMethods(int numRows, int numColumns) {
row = numRows;
col = numColumns;
array = new double[row][col];
}
public void fill() {
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++)
array[i][j] = (double) (Math.random() * 100.00);
}
}
public String toString() {
String method2 = "";
for (int i = 0; i < array.length; i++) {
for (int j = 0; j < array[i].length; j++) {
method2 += String.format("%8.2f", array[i][j]) + " ";
}
method2 += "\n";
}
return method2;
}
public double[] sumRows() {
double[] rowArray = new double[row];
for (int i = 0; i < row; i++) {
sumRow = 0;
for (int j = 0; j < col; j++) {
sumRow = sumRow + array[i][j];
}
rowArray[i] = sumRow;
}
return rowArray;
}
public double[] sumColumns() {
double[] colArray = new double[col];
for (int i = 0; i < col; i++) {
sumCol = 0;
for (int j = 0; j < row; j++) {
sumCol = sumCol + array[j][i];
}
colArray[i] = sumCol;
}
return colArray;
}
public double minValue() {
double minValue = array[0][0];
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < array[j].length; i++) {
if (array[j][i] < minValue) {
minValue = array[j][i];
}
}
}
return minValue;
}
public double maxValue() {
double maxValue = array[0][0];
for (int j = 0; j < array.length; j++) {
for (int i = 0; i < array[j].length; i++) {
if (array[j][i] > maxValue) {
maxValue = array[j][i];
}
}
}
return maxValue;
}
}
And here is the class you requested, TwoDTest.
public class TwoDTest {
public static void main(String[] args) {
if (args.length < 2) {
System.out.println("Usage: TwoDTest row cols");
}
else {
int numRows = Integer.parseInt(args[0]);
int numColumns = Integer.parseInt(args[1]);
TwoDMethods twoD = new TwoDMethods(numRows, numColumns);
twoD.fill();
System.out.print(twoD);
System.out.println("Column sums:");
double[] sumColumns = twoD.sumColumns();
for (double sum : sumColumns) {
System.out.printf("%8.2f ", sum);
}
System.out.println();
System.out.println("Row sums:");
double[] sumRows = twoD.sumRows();
for (double sum : sumRows) {
System.out.printf("%8.2f ", sum);
}
System.out.println();
System.out.println("Smallest number: " + twoD.minValue());
System.out.println("Largest number: " + twoD.maxValue());
}
}
}
I launch class TwoDTest as follows:
java TwoDTest 3 4
And I get the following output:
96.83 11.96 50.86 43.26
89.06 84.86 30.68 59.61
63.51 96.09 49.93 32.19
Column sums:
249.39 192.92 131.47 135.05
Row sums:
202.90 264.21 241.72
Smallest number: 11.962167522763945
Largest number: 96.82621497529537

I need help declaring an array in java

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.

Everytime I run this method my array is reset

Everytime I call set() it resets all the values in the array to false except for what ever the int row int col is because i set that to true before the method ends. Why is this happening I thought I was making a copy of the array B and then setting the values that are in A to the values in B? Or am I mistaken here.
public void set(int row, int col) throws IndexOutOfBoundsException {
if (row >capacityr) {
boolean B[][] = new boolean[row+1][capacityc+1];
for (int k = 0; k < capacityr; k++)
for (int j = 0; j < capacityc; j++)
B[k][j] = a[k][j];
capacityr=row;
a = B;
}
if (col >capacityc) {
boolean C[][] = new boolean[capacityr+1][col+1];
for (int k = 0; k <capacityr; k++)
for (int j = 0; j < capacityc; j++)
C[k][j] = a[k][j];
capacityc=col;
a = C;
}
a[row][col] = true;
pT++;
}
It should be easier to use an ArrayList but I think this would fix your problem.
public void set(int row, int col) throws IndexOutOfBoundsException {
if(row > capacityr) {
if(col > capacityc) {
//both row and col are too big
boolean temp[][] = new boolean[row+1][col+1];
//copy a
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
//set all the new elements to false
for(int i = capacityr+1; i <= row; i++) {
for(int j = capacityc+1; j <= col; j++) {
temp[i][j] = false;
}
}
//set row and col and a to temp
temp[row][col] = true;
a = temp;
//update capacity
capacityr = row;
capacityc = col;
}
else {
//just row is too big
boolean temp[][] = new boolean[row+1][capacityc+1];
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
for(int i = capacityr+1; i <= row; i++) {
temp[i][capacityc] = false;
}
temp[row][col] = true;
a = temp;
capacityr = row;
}
}
else {
if(col > capacityc) {
//just col is too big
boolean temp[][] = new boolean[capacityr+1][col+1];
for(int i = 0; i <= capacityr; i++) {
for(int j = 0; j <= capacityc; j++) {
temp[i][j] = a[i][j];
}
}
for(int j = capacityc+1; j <= col; j++) {
temp[capacityr][j] = false;
}
temp[row][col] = true;
a = temp;
capacityc = col;
}
else {
//neither are too big
a[row][col] = true;
}
}
}

Categories