Merge two 1D array's into a new 1D array. Trouble appending last index
Hello, i am having trouble appending the rest of my original array to my new array.
I am suppose to shuffle two arrays and put the output into a new array.
For instance.
int [] A = {2,3,4,5};
int [] B = {1,5,6,9,123};
A and B are my two arrays that i need to shuffle into array C
So C's output is:
int [] C = {2,1,3,5,4,6,5,9,123}
The problem i encounter is that it doesn't want to append the longer array so my output right now is
int [] C = {2,1,3,5,4,6,5,9,0}
my code is
Code :
int [] A = {2,3,4,5};
int [] B = {1,5,6,9,123};
int Lengthmin = (A.length<B.length? A.length:B.length);
int[] C= new int [A.length+B.length];
for(int i =0;i<Lengthmin;i++)
{
C[2*i]=A[i];
C[2*i+1]=B[i];
}
//didnt include printing the array
Thanks in advanced for any help!
Re: Merge two 1D array's into a new 1D array. Trouble appending last index
Quote:
Originally Posted by
norske_lab
...it doesn't want to ...
It does exactly what you told it to, right? It interleaves elements from the two source arrays into the target array until it gets to the end of the shorter of the source arrays, right?
So...
To use your program as a starting point, you can make a new loop to execute after the first loop. The counter for this new loop can start at the next index of C and will be incremented each time through the loop until all elements of C have been written. Each time it goes through the loop it gets another value from the longer of the source arrays and stores it in the target:
Code :
Begin Loop
If A is shorter, get the value of the next element of B and store in C
If B is shorter, get the value of the next element of A and store in C
End Loop
Heck; I'll kick it off:
Code java:
for (int i = ???; i < C.length; i++) {
C[i] = ??? // Either A[something] or B[something]
}
The only questions are:
- What is the "next index of C" that this loops starts at?
- What is the the source array (is it A or is it B?) and what is the index of the source array value that is copied into C[i] each time through the loop?
If you can't figure the answers in your head, or even with pencil and paper (gasp), then put print statements inside your first loop to see what it has done by the time it gets ready for the second loop.
Cheers!
Z