Public Group

varying length [][] array to single [] array

This topic is 1028 days old which is more than the 365 day threshold we allow for new replies. Please post a new topic.

Recommended Posts

Normally if I want to transfer data from double array of fixed length index to single array (or vice versa), I would code something like:

  for( int i=0; i<width; i++ ){
for( int j=0; j<height; j++ ){
index = i * Width + j;
singleArray[index]  =  doubleArray[i][j];
      }
}


This obviously wouldn't work if the height (or width) is of varying length.

For varying length i've had to write the code below. It works well but looks very convoluted with too many helper variables. I think there must be a more straight forward line of code that should do the same. Is there?

Just trying to avoid writing dumb code

Java, but here I'm sure the language doesn't matters

int rb=0, prevRb=0, culm=0, addOnce=0;

for(int t=0; t<FloatXArry.size(); t++){  //FIXED SIZE

for(int s=0; s<Height[t]; s++){      //VARYING SIZE

if( (addOnce == 0) && (t>0) ){
rb = rb + 1;
prevRb = rb;
}
rb = prevRb + s;
....
....
ObjFloatArray[t][s] = ArrayObj.get( rb )[0];
}
}



Share on other sites

Quite frankly, I don't understand your second code block at all, but I'd do something like this (Java-like, but probably not a real language):

int index = 0;
for( int i = 0; i < doubleArray.length(); i++)
{
for( int j = 0; j < doubleArray[i].length(); j++)
{
singleArray[index++] = doubleArray[i][j];
}
}


The only difference between mapping a rectangular vs. a jagged array is that you can't implcitly get the index based on dimensions, and that you need to store the lengths of the jagged arrays (which java-like languages will do for you.

Edited by SeraphLance

Share on other sites

Just increment rb every time the inner loops runs instead of assigning prevRb+s to it. Then you get get rid of all those other variables and the conditional.

If thats not possible for some reason (eg code you didnt show), you can should be able to eliminate the conditional/extra vars by adding 1 to rb right after the inner loop ends (in outer loop)

Edited by Waterlimon

Share on other sites

@SeraphLance and Waterlimon Your solutions are perfectly correct in the context of what I posted and how you understood the post.

But in actual fact it would't work in the actual code. For simplification reasons I couldn't post the whole code (moreso because it included changes in other places), I tried to over-simplified so it could be contained in one single section but inadvertently removed the core reason why your solution didn't work. The indices changes aren't straight forward.

If I could get a way to contain the code in one place while retaining the actual problem, i would post again

EDIT: too much hassles for this, i'ill stick with what works for now

Edited by greyhounder

1. 1
2. 2
3. 3
Rutin
13
4. 4
5. 5

• 26
• 11
• 9
• 9
• 11
• Forum Statistics

• Total Topics
633700
• Total Posts
3013420
×