• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

2D to 1D

 
John Stevens
Greenhorn
Posts: 5
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Bartender
Pie
Posts: 12017
24
Chrome Java Linux
  • 0
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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.
f
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic