• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

2D to 1D

 
Greenhorn
Posts: 5
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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?
 
lowercase baba
Posts: 13089
67
Chrome Java Linux
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • 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
 
With a little knowledge, a cast iron skillet is non-stick and lasts a lifetime.
reply
    Bookmark Topic Watch Topic
  • New Topic