Link to home
Start Free TrialLog in
Avatar of gudii9
gudii9Flag for United States of America

asked on

midway challege

Hi,

i am trying below challenge

http://codingbat.com/prob/p146449

i wrote as below
public int[] middleWay(int[] a, int[] b) {
 int arrayC[]=new int[2];
 arrayC[0]=a[1];
 
 arrayC[1]=b[1];
  return arrayC;
}

Open in new window


i wrote as above and passed all tests. I wonder how can i improve my code. please advise
SOLUTION
Avatar of ozo
ozo
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
ASKER CERTIFIED SOLUTION
Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of gudii9

ASKER

Hopefully will work for any size array.

i wonder how works for any size other than 3. Let us say array size is 6 then 6/2=3 so
 middleWay[0] = a[3];
        middleWay[1] = b[3];
which may not be what we want in this challenge? please advise
What would be what you want when array size is 6?
Depends what behaviour you desire. a[3] will be the 4th element in the array leaving 2 on the right hand side and 3 on the left hand side. There's no way you can split it evenly.
maybe
  return new int[]{(a[(a.length-1)/2]+a[a.length/2])/2,(b[(b.length-1)/2]+b[b.length/2])/2};
maybe
  return new int[]{(a[(a.length-1)/2]+a[a.length/2])/2,(b[(b.length-1)/2]+b[b.length/2])/2};

Still same issue. I think @gudii9 is asking how to handle arrays that are not equally splittable in half.
In short, you can't.
Avatar of gudii9

ASKER


Given 2 int arrays, a and b, each length 3, return a new array length 2 containing their middle elements.

say if above challenge modified to below


Given 2 int arrays, a and b, each length 3 or 9 or any odd number(i guess other than 1!!), return a new array length 2 containing their middle elements.

Then how to extend my solution to accomodate it. please advise
return new int[]{a[a.length/2],b[b.length/2]};
works for any odd number

return new int[]{(a[(a.length-1)/2]+a[a.length/2])/2,(b[(b.length-1)/2]+b[b.length/2])/2};
also works for any odd number and extends the solution in a symmetric way for even numbers
The solution I posted works for any length
Guddi9 can u tell me if the solution I provided works or not? If not tell me the expected outcome versus actual outcome