File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
The moose likes Java in General and the fly likes 2D to 1D Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Java in General
Bookmark "2D to 1D" Watch "2D to 1D" New topic

2D to 1D

John Stevens

Joined: Oct 24, 2003
Posts: 5
I want to store the values of a 2D array into a 1D array depending on the values of the 2D array.
For example:
int[] oneD = new int [val]; //value of 1D array depends on value of 2D

for (int i = 0; i < oneD.length; i++)//for loop for 1D array
for (int row = 0; row < matrix.length; row++)
for (int col = 0; col < matrix.length; col++)
if(matrix[row][col] > 0)
oneD[i] = matrix[row][col];
If the value of the 2D array is more than zero than store that value in the 1D array.
When I display the values of the 1D array it displays the last value of the 2D array continuously in each element of the 1D array.
How can I correct this?
fred rosenberger
lowercase baba

Joined: Oct 02, 2003
Posts: 11955

because you're putting it there...
your outer loop steps through the one-d array. so, you start at the first element. then, your inner 2 loops step through the 2d array. but each time you get to the assignment, you're sitting on the first element, constantly re-assigning values to it. when you finish the 2d array, your 1st element of the 1-d get assigned the last value of the 2d.
then, you go to the 2nd element of the 1d. keep re-assigning, until the last value in the 2d gets put there...
and so on.
get rid of the outer loop. declare an int outside of the two remaining loops, initialized to 0. then, depending on if you want 0's in your array or not, increment the counter either inside or outside the if block.
i don't want to give too much away, but i hope this helps.

There are only two hard things in computer science: cache invalidation, naming things, and off-by-one errors
I agree. Here's the link:
subject: 2D to 1D
It's not a secret anymore!