Anirudh Anirudh - 3 months ago 20
Java Question

Solving codingBat 'evenOdd' with one loop in Java

The question is about Solving this problem from codingBat in Java.

Problem Statement:

Return an array that contains the exact same numbers as the given array, but rearranged so that all the even numbers come before all the odd numbers. Other than that, the numbers can be in any order. You may modify and return the given array, or make a new array.


evenOdd({1, 0, 1, 0, 0, 1, 1}) → {0, 0, 0, 1, 1, 1, 1}

evenOdd({3, 3, 2}) → {2, 3, 3}

evenOdd({2, 2, 2}) → {2, 2, 2}


The Problem is simple with 2 loops I attempted at solving it with 1 it got too lengthy I believe, is there any other efficient way to solve the above problem using 1 loop?
do not use collections!

My solution:

public int[] evenOdd(int[] nums) {

boolean oddFound=false;
int count=-1;
int oddGap=0;

for(int i=0;i<nums.length;i++)
{
if(!(oddFound)&(nums[i]%2==0))
continue;

if((!oddFound)&(nums[i]%2==1))
{
oddFound=true;
count=i;
continue;
}
if((oddFound)&(nums[i]%2==1))
{
oddGap++;
continue;
}
if((oddFound)&(nums[i]%2==0))
{
int temp=nums[count];
nums[count]=nums[i];
nums[i]=temp;

if(i>0)
i--;

if(oddGap>0)
{
oddGap--;
count+=1;
oddFound=true;
continue;
}
oddFound=false;
}

}
return nums;

}

Answer

Okay! I finally jumped across this question which is actually closed but the solution by asker was almost there apart from failing in 2 cases which I fixed:

I commented out he code by asker which was making it fail in a couple of cases as seen in the question.

I think below is the simplest and most optimized solution:

public int[] evenOdd(int[] nums) {
int y=nums.length,x,a=0;
int temp=0;

for(x=0;x<y;x++)
{
    if(nums[x]%2==0) {
    if(a>(y-2))
       return nums;
    else{
    //nums[a]=nums[a]+nums[x];
    //nums[x]=nums[a]-nums[x];
    //nums[a]=nums[a]-nums[x];

    temp=nums[a];
    nums[a]=nums[x];
    nums[x]=temp;
    a+=1; 
        }

    } 

    return nums; 

    }
Comments