Given! Be! Two! Equal! Long! Arrays:!
int[] a = {1,2,3,4};
int[] b = {10, 20, 30, 40};
Create a new array c that alternately contains all the values of a and b, that is, the value of the array.
then the first value of a, then the first value of b, then the second value of a, etc.
Your output in the example should look like this
[0]!1!
[1]!10!
[2]!2!
[3]!20!
[4]!3!
[5]!30!
[6]!4!
[7]!40!
Your function should work for any value (and any number of values) for any number of values for a and b.
as long as the length of both a and b is the same.
Now I have made two for loops.
This is my solution but its not correct:
I like your attitude. You ask for a hint, not a solution.
With for loops you can loop through c[] and with each step either pick value from a[] or b[]. Second choice is a bit similar what you have started with. Loop through length a[]. With each value of i you first add a value from a[] to c[] and then a value from b[] to c[]. Trick is in how you construct index for c[].
If this was too cryptic, ask and I’ll help you a bit more.
I suggest that you use the approach presented by @SomeOne perhaps this will make it clearer
Loop through length `a[]`. With each value of `i` you
add a value from `a[]` to the *next available* element in `c[]`
add a value from `b[]` to the *next available* element in `c[]`
All you need is a variable to remember the next available element. Think about it, at the beginning the first available element is at [0], the net avialble is [1] and the one after that [2] and so on.
You don’t actually need to remember the next available element if you are smart with indexing. From a[] index is i*2 and from b[] index is i*2+1. That’s actually how even and odd numbers are defined in mathematics.
True, I was just trying to avoid the maths, to me it seemed simpler to have a variable that you increment by 1 each time you store a value in c[]. In fact using post increment ++ can make the code even less verbose and more efficient.
You are probably right. I was thinking problem as an experienced programmer. I’d do believe that the most elegant solution is the best one, but it’s not one that you come by easily and thus not suitable for beginners.
Hi. It’s simpler than you think!
You need to step through c in increments of 2. This means a single for loop: for (int i = 0; i < c.length; i+=2)
then in this loop assign a[i/2] to c[i] and then b[i/2] to c[i+1]
Done!