Array element subtraction index out of bounds - java

Im trying to subtract the same element from a different array i.e., [0,0] - [0,0] and [0,1] - [0,1] but I'm just getting an array index out of bounds exception and I can't seem to work out why. Can anyone see a problem with the code?
//pixArray and avgPix already contain data
int[][] pixArray = new int[35][10];
int[][] avgPix = new int[35][1];
int[][] correctImg = new int[35][10];
public void correctImage() {
for (int r = 0; r < correctImg.length; r++) {
for (int c = 0; c < correctImg[r].length; c++) {
correctImg[r][c] = avgPix[r][c] - pixArray[r][c];
System.out.println(correctImg[r][c]);
}
}
}
I also need to change the loop so that avgPix only loops every time the pixArray column is 0 because avgPix only has 1 column can anyone suggest how I can do this?

You are running r and c based on correctImg's dimension [35][10] and avgPix has dimensions of [35][1]
int[][] avgPix = new int[35][1];
The loop in the provided code snippet uses r and c value from the outer/inner for loop, based on what's described in the question it will make sense to use avgPix[r][0] for all pixArray[r][c].
Not sure what you are trying to achieve but something like this will calculate difference with average
correctImg[r][c] = avgPix[r][0] - pixArray[r][c]

I am not sure if i get you, but if you need to execute the correctImg[r][c] = avgPix[r][c] - pixArray[r][c]; command only when c=0 then you dont need a loop
public void correctImage() {
for (int r = 0; r < correctImg.length; r++) {
correctImg[r][0] = avgPix[r][0] - pixArray[r][0];
}
}
Edit
after reading your comment on your question, i am still not sure what you are trying to do, (looping avgPix every 10th time?).
Maybe an IF statement is more appropriate

The second (useless) dimension of the avgPix is length 1, but the other arrays that you iterate over of length 10. This means that when c > 0, those data points do not exist in avgPix.
In fact, because the second dimension of that array is length 1, it's pretty much useless. Instead, you should just not worry about a second dimension at all. To make it obvious:
int[][] pixArray = new int[35][10];
int[][] avgPix = new int[35]; //no need for 2D array, since it is an average of row values
int[][] correctImg = new int[35][10];
public void correctImage() {
for (int r = 0; r < correctImg.length; r++) {
int rowAverage = avgPix[r]; //this doesn't depend on c
for (int c = 0; c < correctImg[r].length; c++) {
correctImg[r][c] = rowAverage- pixArray[r][c];
System.out.println(correctImg[r][c]);
}
}
}

Related

How to copy a 2-dimensional array in java

I just began studying java. One of the tasks was to create a function to create a reverse 2-dimensional array, for example, if the input array was {1,2}{3,4}, the new array must be {4,3}{2,1}. The code below is the method I created. The problem is that the old array d is affected by the loop along with c, so, in this case, it copies half of the values into c, but also replaces the last half of d, so the second half of c is just a mirrored first half, basically, in the example case both c and d will be like this in the end: {4,3}{3,4}. I checked c==d and c.equals(d) after cloning, both show false.
Also, I tried using Arrays.copy, the result was the same. Plus I want the method to work on the arrays that can have their sub-arrays with different lengths, for example, {1,2}{3}{4,5}, and I don't know if it'll work on such arrays.
static int[][] reversematrix(int[][] d) {
int[][] c = d.clone();
for (int i = d.length-1, x = 0; i >= 0; x++, i--) {
for (int j = d[i].length-1, y = 0; j>=0; y++, j--) {
c[x][y] = d[i][j];
}
}
return c;
Can you tell me how to make d(imput array) unaffected by the method/loop? I think the problem is in copying, so I'd love to know a proper way of copying a 2D array into a new object, but if it is in something else, please tell me waht it is.
UPD: Thanks to #sascha the solution was found. Here's the code if someone is interested:
static int[][] reversematrix(int[][] d) {
int[][] c = new int[d.length][];
for (int i = d.length-1, x = 0; i >= 0; x++, i--) {
c[x] = new int[d[i].length];
for (int j = d[i].length-1, y = 0; j>=0; y++, j--) {
c[x][y] = d[i][j];
}
}
return c;
}

Produce repmat() method using java

we have the repmat(arr,2,1,2) method in matlab produce a format which is :
arr = [6,3,9,0];
L(:,:,1) =
6 3 9 0
6 3 9 0
L(:,:,2) =
6 3 9 0
6 3 9 0
the java code that i tried to produce same format is
class test24{
public static void main ( String [] args ) {
int[] arr = {6,3,9,0};
test24 test = new test24();
System.out.println(Arrays.deepToString(test.repmat(arr,2,1,2)));
}
public static int[][][] repmat (int[] array, int rows, int columns, int depth)
{
int arrayColumns = array.length;
int resultColumns = arrayColumns * columns;
int[][][] result = new int[rows][resultColumns][depth];
int z = 0;
for (int d = 0; d < depth; d++)
{
for (int r = 0; r < rows; r++)
{
for (int c = 0; c < resultColumns; c++)
{
result[r][c][d] = array[z++];
if (z >= arrayColumns)
{
z = 0;
}
}
}
}
return result;
}
}
the the result from the java code is :
[[6,6],[3,3],[9,9],[0,0]],[[[6,6],[3,3],[9,9],[0,0]]???
please any suggestion
I believe that the depth argument causes that each value within the array has two values (int[][][] result = new int[rows][resultColumns][depth]; would become (given the inputs rows=2, columns=1 and depth=2 and an initial array of 4) new int[2][1][2]).
Not entirely sure what the repmat method exactly should do put it might be that changing the creation of the array into int[][][] result = new int[depth][rows][resultColumns]; fixes the issue.
I imagine that this is because MATLAB used column-major indexing whereas Java uses Iliffe vectors. So MATLAB stores multidimensional vectors using a single contiguous block of memory where Java stores an array of pointers and each pointer points to another array.
It's difficult to tell exactly what the Java data-structure your code resulted in was. Do you think maybe you could rather post a screen shot from a debugger? What you have now does not look correct, the brackets don't even match.
At a guess though, I would suggest that you maybe change this line
result[r][c][d] = array[z++];
To something more like
result[d][r][c] = array[z++];
Or possibly to even alter the inner loop to something like
for (int c = 0; c < columns; c++) {
result[d][r][c] = array;
}

Transferring the contents of a one-dimensional array to a two-dimensional array

I'm trying to make an encryption program where the user enters a message and then converts the "letters into numbers".
For example the user enters a ABCD as his message. The converted number would be 1 2 3 4 and the numbers are stored into a one dimensional integer array. What I want to do is be able to put it into a 2x2 matrix with the use of two dimensional arrays.
Here's a snippet of my code:
int data[] = new int[] {10,20,30,40};
*for(i=0;i<2;i++)
{
for(j=0;j<2;j++)
{
for (int ctr=0; ictr<data.length(); ictr++){
a[i][j] = data[ctr];}
}
}
I know there's something wrong with the code but I am really lost.
How do I output it as the following?
10 20
30 40
(instead of just 10,20,30,40)
Here's one way of doing it. It's not the only way. Basically, for each cell in the output, you calculate the corresponding index of the initial array, then do the assignment.
int data[] = new int[] {10, 20, 30, 40, 50, 60};
int width = 3;
int height = 2;
int[][] result = new int[height][width];
for(int i = 0; i < height; i++) {
for(int j = 0; j < width; j++) {
result[i][j] = data[i * width + j];
}
}
Seems like you want to output a 2xn matrix while still having the values stored in a one-dimensional array. If that's the case then you can to this:
Assume the cardinality m of your set of values is known. Then, since you want it to be 2 rows, you calculate n=ceil(m/2), which will be the column count for your 2xn matrix. Note that if m is odd then you will only have n-1 values in your second row.
Then, for your array data (one-dimension array) which stores the values, just do
for(i=0;i<2;i++) // For each row
{
for(j=0;j<n;j++) // For each column,
// where index is baseline+j in the original one-dim array
{
System.out.print(data[i*n+j]);
}
}
But make sure you check the very last value for an odd cardinality set. Also you may want to do Integer.toString() to print the values.
Your code is close but not quite right. Specifically, your innermost loop (the one with ctr) doesn't accomplish much: it really just repeatedly sets the current a[i][j] to every value in the 1-D array, ultimately ending up with the last value in the array in every cell. Your main problem is confusion around how to work ctr into those loops.
There are two general approaches for what you are trying to do here. The general assumption I am making is that you want to pack an array of length L into an M x N 2-D array, where M x N = L exactly.
The first approach is to iterate through the 2D array, pulling the appropriate value from the 1-D array. For example (I'm using M and N for sizes below):
for (int i = 0, ctr = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j, ++ ctr) {
a[i][j] = data[ctr];
}
} // The final value of ctr would be L, since L = M * N.
Here, we use i and j as the 2-D indices, and start ctr at 0 and just increment it as we go to step through the 1-D array. This approach has another variation, which is to calculate the source index explicitly rather than using an increment, for example:
for (int i = 0; i < M; ++ i) {
for (int j = 0; j < N; ++ j) {
int ctr = i * N + j;
a[i][j] = data[ctr];
}
}
The second approach is to instead iterate through the 1-D array, and calculate the destination position in the 2-D array. Modulo and integer division can help with that:
for (int ctr = 0; ctr < L; ++ ctr) {
int i = ctr / N;
int j = ctr % N;
a[i][j] = data[ctr];
}
All of these approaches work. Some may be more convenient than others depending on your situation. Note that the two explicitly calculated approaches can be more convenient if you have to do other transformations at the same time, e.g. the last approach above would make it very easy to, say, flip your 2-D matrix horizontally.
check this solution, it works for any length of data
public class ArrayTest
{
public static void main(String[] args)
{
int data[] = new int[] {10,20,30,40,50};
int length,limit1,limit2;
length=data.length;
if(length%2==0)
{
limit1=data.length/2;
limit2=2;
}
else
{
limit1=data.length/2+1;
limit2=2;
}
int data2[][] = new int[limit1][limit2];
int ctr=0;
//stores data in 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
data2[i][j] = data[ctr];
ctr++;
}
else
{
break;
}
}
}
ctr=0;
//prints data from 2d array
for(int i=0;i<limit1;i++)
{
for(int j=0;j<limit2;j++)
{
if(ctr<length)
{
System.out.println(data2[i][j]);
ctr++;
}
else
{
break;
}
}
}
}
}

Finding plateau in Java Array

I having a really hard time finding a plateau within an array. What I'm looking for is length and location of the longest sequence of equal values where the numbers on both sides are smaller. Now I know there could be two or more valid plateaus with same length ideally I would like to print the plateau with a higher value.
I have created an array[40] and a Random obj. To fill the array, once I have filled it I know I will need a loop to check the indexes. But thats where the confusion comes in. I have tried using a for loop to find the plateau but my results would just increase the value stored within the index.
Any points in the right direction I would greatly appreciate it.
import java.util.Random;
public class Plateau {
public static void main(String[]args)
{
int[] array1 = new int[40];
Random genrator = new Random();
for (int i = 0; i < array1.length; i++)
{
array1[i] = genrator.nextInt(21 - 1);
}
for(int i = 0; i < array1.length; i++)
{
System.out.print(array1[i] + " ");
}
System.out.println("\n");
for (int i = 0; i < array1.length; i++)
{
if (array1[i] < array1[i] + 1)
{
System.out.println(array1[i] + " ");
}
}
}
}
In pseudo-code:
V value=first value
P position=1
L length=0
Scan the values from position Q=2
Compare current value C to V
If C is less than V
if this sequence Q-P is longer than L
save length as L
save P as location R
update V and P to current value
If C is greater than V
update V and P to current value
I don't have a compiler for pseudo-code so it might not be exactly right, but it should be a start.

Transposing Values in Java 2D ArrayList

Good evening all,
I'm trying to write a method that creates and returns a 2D array whose elements in each location are the same as the elements in the mirror image location of the parameter array. Unfortunately, no matter what pair of numbers I enter into the method call I get an "out of bounds" error in my compiler. Below is my program. Tell me where I've gone wrong! Thanks!
public static int[][] transpose(int [][] a) {
int r = a.length;
int c = a[r].length;
int [][] t = new int[c][r];
for(int i = 0; i < r; ++i) {
for(int j = 0; j < c; ++j) {
t[j][i] = a[i][j];
}
}
return t;
}
}
Arrays in java are 0 based, change your assignment to c to :
int c = a[r - 1].length;
#Suraj is correct, however you must assume the 2D array is rectangular, in which case it is sightly more efficient to change line 3 to:
int c = a[0].length;
#Kris answer text is correct however code sample is wrong line.
Note this error is a reproduction of a broken "answer" posted in "Yahoo Answers": http://answers.yahoo.com/question/index?qid=20080121204551AAn62RO
Your problem lies in line two: a[r].length returns the number of columns, but arrays are indexed from 0. You should adjust accordingly:
int r = a.length - 1;

Categories

Resources