This week's giveaways are in the MongoDB and Jobs Discussion forums.
We're giving away four copies of Mongo DB Applied Patterns and 4 resume reviews from Five Year Itch and have the authors/reps on-line!
See this thread and this one for details.
The moose likes Java in General and the fly likes 2D to 1D Big Moose Saloon
  Search | Java FAQ | Recent Topics
Register / Login


Win a copy of Mongo DB Applied Patterns this week in the MongoDB forum
or a resume review from Five Year Itch in the Jobs Discussion forum!
JavaRanch » Java Forums » Java » Java in General
Reply Bookmark "2D to 1D" Watch "2D to 1D" New topic
Author

2D to 1D

John Stevens
Greenhorn

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
Bartender

Joined: Oct 02, 2003
Posts: 9939
    
    6

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


Never ascribe to malice that which can be adequately explained by stupidity.
 
I agree. Here's the link: http://zeroturnaround.com/jrebel - it saves me about five hours per week
 
subject: 2D to 1D
 
Similar Threads
2 dimensional array without hard coding values
Write a method that can be called, that will initialize the seating plan.
Pass file into 2d array
Manipulating Vectors (code not working)
Learning Project 2