How to handle ArrayIndexOutofBounds while printing array in snake form - java

I have a requirement to print the matrix in a snake form. So for this matrix, the output should be:
My question is that this code throws ArrayIndexOutofBounds. How can I handle that to avoid this?
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
int row=mat.length;
int col=mat[0].length-1;
int c=col;
int r=0;
while(r < row) {
for(int j=c;j>=0;j--) {
// System.out.print("r: " + r);
// System.out.print(" " + mat[r][j]);
}
r=r+1;
for(int j=0;j<=c;j++) {
// System.out.print("r: " + r);
//System.out.print(" " + mat[r][j]);
}
r=r+1;
}
3 2 1 4 5 6 9 8 7

This is how I would have gone about it:
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
int row=0;
while(row < mat.length) {
if(row%2 == 0){ //if an even row, go right to left
int col = mat[0].length - 1;
while(col >= 0) { System.out.print(mat[row][col]); col--; }
}else {
int col = 0;
while(col < mat[0].length) { System.out.print(mat[row][col]); col++; }
}
row++;
}
where you are going wrong is in incrementing r inside the loop and not checking if it's still less then the length before printing.
you can also add this check to your code for it to start working:
.
.
r=r+1;
if(r >= row)
break;
for(int j=0;j<=c;j++) {
.
.
.

I see that the second line says:
int row=mat.length;
Because array indexes start at 0, you should change it to:
int row=mat.length-1;
to avoid getting an exception when calling mat[row].

Here is one way. It is important to take the row length to allow for ragged arrays.
int[][] mat = { { 1, 2, 3
}, { 4, 5, 6
}, { 7, 8, 9, 10, 11
}, { 12, 13
}, { 14, 15, 16, 17, 18, 19
}
};
for (int r = 0; r < mat.length; r++) {
if (r % 2 == 0) {
for (int c = mat[r].length - 1; c >= 0; c--) {
System.out.print(" " + mat[r][c]);
}
}
else {
for (int c = 0; c < mat[r].length; c++) {
System.out.print(" " + mat[r][c]);
}
}
}
Note that if you want to snake left to right, then modify it to use r % 2 == 1. If you want to go bottom up, change your outer loop to start at the last row.

Your code throws ArrayIndexOutOfBounds exception because r becomes 3 (r=r+1) on second iteration and you try to access mat[3][2] (ie. you are accessing the values of fourth row which is not available)
for(int row = 0; row < mat.length; row++){
if(row%2 == 0) {
// print the elements in reverse order
}
else {
//print the elements as in given matrix
}
}
Thus all your odd rows' (ie. 1st, 3rd, 5th row..) elements will be printed in reverse order and even rows' elements will be printed as in given matrix

Instead of initializing so many variables you can just set up the for loops which first determine if we are starting at the end or beginning of the row and then iterate over all the integers.
int[][] mat= {{1,2,3},{4,5,6},{7,8,9}};
for(int row = 0; row < mat.length; row++){
if(row%2 == 0){
for(int col = mat[row].length -1; col >= 0; col--){
System.out.print(mat[row][col] + " ");
}
}else{
for(int col = 0; col < mat[row].length; col++){
System.out.print(mat[row][col] + " ");
}
}
}

Related

How to add integers from one two dimensional array and create a new two dimensional array

I am trying to solve a problem where one two dimensional array(A) is
1 1 0
1 1 0
1 1 0
and the resulting two dimensional array(B) is
1 2 2
2 4 4
3 6 6
Each point in B is sum of corresponding entry in A, plus all entries to the left and above it.
Here is what I have done so far
public static void main(String[] args)
{
int[][] arrA = { { 1, 1,0 }, { 1, 1,0 },{ 1, 1,0 } };
int[][] arrB = new int [3] [3];
for (int i = 0; i < arrA.length; i++) {
for (int j = 0; j < arrA.length; j++) {
System.out.print(arrA[i][j] + " ");
}
System.out.println();
}
System.out.println();
for (int r=0; r<arrB.length; r++) {
for(int c=0; c<arrB[r].length; c++) {
arrB[r][c] = r * c;
}
}
for(int r=0; r < arrB.length; r++) {
for(int c=0; c < arrB[r].length; c++) {
// if((r==0 || r==(arrA.length-1)) || (c==0 || c==(arrA.length-1)) )
arrB[r][c] = r+c;
System.out.print(arrB[r][c]+" ");
}
System.out.println();
}
}
}
The answer I get is
0 1 2
1 2 3
2 3 4
The question I have is how can I get the correct numbers in array B. What code have I missed?
Each value of B can be be calculated as :
B(i,j) = B(i-1,j-1) + B((i-1,j) - (i-1,j-1)) + A(i,j) + B((i,j-1)-(i-1,j-1))
This is because:
Diagonal value (i-1,j-1) is sum of all left and top value of (i,j) excluding immediate top and left values.
Left value (i, j-1) is sum of immediate left values + diagonal value.
Top value (i-1,j) is sum of immediate top values + diagonal values.
so, by combining these 3 values and the current element we get the value of B(i,j)
Here is the updated code :
public static void main(String args[]) {
int[][] arrA = { { 1, 1,0 }, { 1, 1,0 },{ 1, 1,0 } };
int [][]B = new int [3][3];
int diag, i, j,top,left;
int len = arrA.length;
int bredth = arrA[0].length;
for( i=0;i<len;i++){
for( j=0;j<bredth;j++) {
diag = 0; top=0; left=0;
if(i-1>=0 && j-1>=0) {
diag = B[i-1][j-1];
}
if(i-1>=0) {
top = B[i-1][j];
}
if(j-1>=0) {
left = B[i][j-1];
}
B[i][j] = diag + arrA[i][j] + (top-diag) + (left-diag);
}
}
for(i=0;i<3;i++) {
for(j=0;j<3;j++) {
System.out.print(B[i][j]);
}
System.out.println();
}
}
Issue with your code is you are just adding indexes and not taking into consideration values. But as per your question each value of B should be equal to sum of corresponding entry in A, plus all entries to the left and above it
for(int r=0; r < arrB.length; r++) {
for(int c=0; c < arrB[r].length; c++) {
// if((r==0 || r==(arrA.length-1)) || (c==0 || c==(arrA.length-1)) )
arrB[r][c] = r+c; //Here `r` and `c` are just indexes value not actual value
System.out.print(arrB[r][c]+" ");
}
System.out.println();
}

Finding consecutive elements of an array using Java

I'm almost new at Java! I want to control if there are 4 consecutive elements in an array with 5 elements. Is there any way to do that? Can someone help me with that? Thanks! Consecutive like {2, 3, 4, 5}. If there is {3, 4, 2, 5} for example this is not consecutive.I want just a simple example if someone can help me.
I did this but I think this is incorrect:
public int katerTeNjepasnjeshme()
{
int[] numrat=new int[zar.length];
for(int i=0;i<zar.length;i++)
numrat[i]=zar[i].getValue();
int shuma=0;
for(int i=0;i<zar.length-1;i++)
{
if(zar[i+1].getValue()==(zar[i].getValue()+1))
Joptionpane.showMessageDialog(null,"Tere are cons elements");
}
Here's the general idea:
Keep a counter (initialized appropriately), to keep track of the number of consecutive elements as you iterate over the elements.
If the counter reaches 4, you have found 4 consecutive elements.
If you encounter an element that is not consecutive, then reset the counter to 1, and proceed to check the next element.
Here is a sample code snippet:
public static void findConsecutive()
{
int[] array = {1,2,3,5,6,7,8,10};
int counter = 1;
int i = 1;
for (i = 1; i < array.length; i++)
{
if (array[i] == (array[i-1] + 1))
{
counter++;
if (counter == 4)
{
System.out.println("Consecutive elements are at array index: " + (i - 3) + " to " + i);
break;
}
}
else
{
counter = 1;
}
}
}
i think something like that should work:
int[] mylist = new int[10];
for (int i = 0; i < myList.length; i++) {
int k = 1;
for (int j = 1; j < 5 j++) {
if (mylist[i] == mylist[i+j]-j) {
k++;
}
if (k=5) System.out.println("found");
}
}
As soon as you need to compare two elements of the array you should use proper bounds in the loop, otherwise you will get ArrayIndexOutOfBoundsException
boolean consequtive = true;
for (int i = 0; i < zar.length - 1; i++)
if (zar[i+1].getValue() != zar[i].getValue() + 1) {
consecutive = false;
break;
}
if (consequtive)
Joptionpane.showMessageDialog(null,"Tere are cons elements");

java : Sum of Vertical elements in a triangle

I want to calculate the sum of all vertical elements in an triangle for example, if the triangle is
Ex : Triangle size is 5
1
2 2
5 2 2
2 0 5 8
8 7 9 4 5
Then the sum should be
Sum1 = 1+2+5+2+8 = 18 (Sum of vertical elements from the first column)
Sum2 = 2+2+0+7 = 11
Sum3 = 2+5+9 = 16
Sum4 = 8+4= 12
Sum5 = 5 = 5
Note : The triangle size will vary, also the elements will be random.
Program I wrote, but it's only calculating the first row how do i calculate and store the 2nd, 3rd and upto the last ?
public class fsdhs
{
public static void main(String args[])
{
int arr[]={1,2,2,5,2,2,2,0,5,8,8,7,9,4,5};
int x,y,count=0,size=5,sum=0;
boolean flag=false;
for(x=0;x<size;x++)
{
for(y=0;y<=x;y++)
{
if(flag==false)
{
sum=sum+arr[count];
flag=true;
}
System.out.print(arr[count]+" ");
count++;
}
System.out.print("\n");
flag=false;
}
System.out.print("\nSum1="+sum);
}
}
You can simplify your code and calculate col sums using the following formula to get index of array by index of i-th row in triangle and j-th column (j<=i, zero-based):
index = i*(i+1)/2 + j
For example, in given triangle at row i=3, column j=2 value is 5, so
index = 3*4/2 + 2 = 8, arr[8] is also 5
A more intuitive approach may be to use a multidimensional jagged array to store the triangle data. This way you can reason over the coordinates directly without needing to calculate row based offsets:
int arr[][]={{1},{2,2},{5,2,2},{2,0,5,8},{8,7,9,4,5}};
int size=5;
for(int x=0; x < size; x++)
{
int sum = 0;
for(int y=x; y < size; y++)
{
sum += arr[y][x];
}
System.out.println("Column " + x + " Sum=" + sum + "\n");
}
You just need to be wary of the uneven row sizes of the jagged array
IdeOne Demo
int SIZE = 5; // The size of your triangle
int arr[]={1,2,5,2,8,2,2,0,7,2,5,9,8,4,5}; // Array of triangle items
int[] sums = new int[SIZE];
for (int i = 0; i < arr.length; i += SIZE, SIZE--) {
for(int j = i; j < i + SIZE; j++) {
sums[sums.length - SIZE] += arr[j];
}
}
// Show items
for (int i = 0; i < sums.length; i++) {
System.out.println("item " + i + ": " + sums[i]);
}

Java using for-loop to produce series of numbers

I am trying to write a collection of for-loops that produce the following series of numbers below. I am trying to accommodate my loops to print each series on the same line, with spaces between each term. I am new to java and got really confused on how exactly I can accomplish it. On the right side are the digits I am increasing the counting by.
1. 4 5 6 7 8 9 10 (+1)
2. 6 5 4 3 2 1 (-1)
3. 2 4 6 8 10 12 14 16 (+2)
4. 19 17 15 13 11 9 7 5 (-2)
5. 7 15 23 31 39 (+8)
6. 2 4 8 16 32 64 (*2)
Here is the code the way I tried to accomplish it. I got the first row to work but I'm wondering weather there's an easy way I can create the rest of them without re-duplicating the program.
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run()
{
{
for(int row = 1; row < 2; row++)
{
print(" " + row + ". ");
for (int col = 4; col < 11; col++)
{
print(row*col + " ");
} //col values
println( );
} //row values
}
}
}
I am new to java and right now going over for-loops and trying to accomplish this in for-loop. If someone could help me out, I would really appreciate it.
Thank you!
Edit:
Here is what happens when I increase the number of rows.
Edit:
Here is the solution of what I had tried accomplishing. Thanks to everyone who helped me.
import acm.program.*;
public class ppLoop extends ConsoleProgram
{
public void run()
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
print(i + ". "); // print row number 1
for (int j = 4; j < 11; j++) // loop for row 1
{
print(j + " ");
}
println( );
print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
print(j + " ");
}
println();
print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
print(j + " ");
}
println();
print((i + 3) + ". ");
for (int j = 19; j > 4; j = j - 2) // loop for row 4
{
print(j + " ");
}
println();
print((i + 4) + ". ");
for (int j = 7; j < 40; j = j + 8) // loop for row 5
{
print(j + " ");
}
println();
print((i + 5) + ". ");
for (int j = 2; j < 65; j = j * 2) // loop for row 6
{
print(j + " ");
}
println();
}
} //close outer loop
} //close public run
} //close console program
You can perform this program with a series of nested loops. I have done the first three rows. I took out your package and used a main method. Also, your indentation was very confusing. Since your increment changes each line, I don't know of a way to make it any shorter than this using for loops.
public class ppLoop{
public static void main(String[] args)
{
{
for(int i = 1; i < 2; i++) // One iteration of outer loop
{
System.out.print(i + ". "); // print row number
// you can use the same variable for each inner loop
for (int j = 4; j < 11; j++) // loop for row 1
{
System.out.print(j + " ");
}
System.out.println( );
System.out.print((i + 1) + ". ");
for (int j = 6; j > 0; j--) // loop for row 2
{
System.out.print(j + " ");
}
System.out.println();
System.out.print((i + 2) + ". ");
for (int j = 2; j < 17; j = j + 2) // loop for row 3
{
System.out.print(j + " ");
}
}
}
}
}
You could create a method that takes:
1. A start number
2. What math operation to perform (add, subtract, or multiply)
3. What number to increment/decrement or multiply by
4. An end number
It would look similar to this:
public void formattedFor(int startNum, String operation, int num, int endNum) {
if (operation.equals("add")) {
for (int i = startNum; i < endNum; i += num) {
System.out.print(i + " ");
}
}
if (operation.equals("sub")) {
for (int i = startNum; i > endNum; i -= num) {
System.out.print(i + " ");
}
}
else if (operation.equals("mult")) {
for (int i = startNum; i < endNum; i *= num) {
System.out.print(i + " ");
}
}
System.out.println( );
}
If I'm understanding the problem, you want to print six series that each start with a different number and increment/decrement that number by some value. Since I see no relationship between the initial value and the increment/decrement, you're going to have to write six separate for loops.
If you're absolutely averse to this, you can store your initial values, your increments/decrements, and your final values in an array and iterate through them using a for loop, an if statement (to deal with the multiplication) and a while loop. The array would look like this:
int[][] values = new int[][] {
{4, 6, 2, 19, 7, 2},
{1, -1, 2, -2, 8, 2},
{10, 1, 16, 5, 39, 64}
};
I could write up the source based on this, but it's not what you asked for.
I strongly suspect that, if this is a homework assignment and you've modified the problem, there's something you've failed to understand about the problem itself. If this is meant to have an simple solution that uses for loops, there should probably be some logic that binds the rows together, unless you're allowed to use arrays/while loops/for loops/objects and methods.
On another note, you should format your code differently. It's somewhat difficult to read right now. In general, indent things that happen inside loops, classes, or functions. For example:
import acm.program.*;
public class ppLoop extends ConsoleProgram {
public void run() {
for(int row = 1; row < 2; row++) {
print(" " + row + ". ");
for (int col = 4; col < 11; col++) {
print(row*col + " ");
} //col values
println( );
} //row values
}
}

Math and Arrays

I'm new to java and still learning. I am having one heck of a time trying to figure out how to create this program. I have tried multiple ways and spent about 4 hours now trying to get this to work and it still wont outprint what I need it to. I need a 10x5 array with the first 25 digits being the index variable squared and the last 25 digits being the index times 3. What it is outprinting is 5 numbers over and over 10 times. But it's like it is not reading the "next index variable". I get: 0.0, 1.0, 4.0, 9.0, 16.0, 0.0, 1.0, 2.0, 4.0, etc.. Here is what I have so far(please don't rate down, I'm trying hard to learn this!):
public class snhu4 {
public static void main(String args[]) {
double alpha[][] = new double [10][5];
for (int col=0; col<=9;col++) {
for (int row=0; row<=4;row++) {
alpha[col][row]= Math.pow(row,2);
System.out.println(alpha[col][row]);
}
}
}
}
I believe you're looking for something like this:
public static void main (String[] args) {
double[][] alpha = new double[10][5];
for (int i = 0; i < 10; i++) {
for (int j = 0; j < 5; j++) {
int index = (5 * i + j);
if (index < 25) {
alpha[i][j] = (index * index);
System.out.println("index(" + index + ")^2 =" + alpha[i][j]);
} else {
alpha[i][j] = (3 * index);
System.out.println("3*index(" + index + ") = " + alpha[i][j]);
}
}
}
}
You need an index variable initialized to zero outside of the loops and incremented (index++) inside the inner loop. Then you can perform the calculations on the index (0-49) rather than the row variable, which keeps looping 0-4. You'll also need a conditional (if statement) that performs one calculation if index is < 25 and a different calculation if index >= 25.
This is just a generalised version, compared to the accepted answer. It will give the same output, though.
public static void main(String args[]) {
double alpha[][] = new double [10][5];
int index = 0;
for (int row = 0; row < alpha.length; row++)
{
for (int col = 0; col < alpha[row].length; col++)
{
if (index < 25)
alpha[row][col] = Math.pow(index, 2);
else
alpha[row][col] = index * 3;
index++;
System.out.println(alpha[row][col]);
}
System.out.println("" + '\n');
}
}
You're always using the row variable to calculate the assignment value, I think you should combine the values of row and col (or maybe use an index as aetheria says), something like this:
double alpha[][] = new double[10][5];
for (int col = 0; col <= 9; col++) {
for (int row = 0; row <= 4; row++) {
if (col < 5) //if column >= 5 that means that you just passed the 25 index
alpha[col][row] = Math.pow(row + (col*row), 2);
else {
alpha[col][row] = Math.pow(row + (col*row), 3);
}
}
}
I couldn't test it (my eclipse is totally crushed) but I think that will give you the idea (probably you will need to play with the "row + (col*row)" part, when one of the variables is 0 it will not fit your needs). Hope this helps, regards.

Categories