简体   繁体   中英

java assign even elements to even index and odd to odd places and if the numbers are not equal add zeros to the places

I am trying to write code to display the even elements to even indexes and odd to odd indexes and if the numbers added numbers are same then add zeros accordingly.

Example:

x = [1,2,3,4] output: 2 1 4 3 x = [1 1 1 4] output: 4 1 0 1 0 1

I reached to get even and odd positions but stuck after that.

Below is my code.

import java.util.*;

class ArrayDemo3 {
    
    public static void main(String[] args) {
        Scanner s = new Scanner(System.in);
        System.out.println("Enter Size of Array :: ");
        int size = s.nextInt();
        int[] x = new int[size];

        System.out.println("Array Created having the size :: " + size);
        System.out.println("Enter Elements for Array :: ");
        for (int i = 0; i < size; i++) {
            System.out.println("Enter element no-" + (i + 1) + " ::");
            x[i] = s.nextInt();
        }

        System.out.println("Contents of Array ::");
        for (int i = 0; i < size; i++) {
            System.out.print(x[i] + "  ");
        }
        
        for (int i = 0; i < size; i = i + 1) {
            int even = 0;
            int odd = 1;
            if (i < size && x[i] % 2 == 0) {
                System.out.print("even : ");
                even = even + i;
                System.out.print("position" + i + " " + x[i] + "  ");
            } else {
                System.out.print("odd : ");
                odd = odd + i;
                System.out.print(i + " " + x[i] + "  ");
            }
            if (even < size && odd < size) { 
                int temp = x[even]; 
                x[even] = x[odd]; 
                x[odd] = temp; 
            } else {
                        
            }
            //System.out.print(x[i] + "  ");
        }
    }

}
     

You can break up your problem in 3 parts:

  1. First create two lists, one containing in encountered order the even numbers and the other the odd numbers:
    private static List<List<Integer>> createOddityLists(int... numbers) {
        List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());

        List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
        numsByOddity.add(new ArrayList<>()); // List of odd numbers
        numsByOddity.add(new ArrayList<>()); // List of even numbers

        numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
        return numsByOddity;
    }
  1. Pad the shorter of the two lists with zeros ( 0 s) to make it equal length as the other one:
    private static void padShorterList(List<List<Integer>> numsByOddity) {
        int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
        int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
        List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
        numsByOddity.get(listIndexToBePadded).addAll(padding);
    }
  1. Finally join intertwining both lists:
    private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
        List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
        for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
            resultList.add(idx * 2, numsByOddity.get(0).get(idx));
        return resultList;
    }

The following is the full working example:

public class ArrayRearrangement {

    public static void main(String[] args) {
//      int[] result = rearrange(1, 2, 3, 4);
        int[] result = rearrange(1, 1, 1, 4);
        System.out.println(Arrays.stream(result).boxed().collect(Collectors.toList()));
    }

    private static int[] rearrange(int... numbers) {
        List<List<Integer>> numsByOddity = createOddityLists(numbers);
        padShorterList(numsByOddity);
        return joinLists(numsByOddity).stream().mapToInt(i->i).toArray();
    }

    private static List<List<Integer>> createOddityLists(int... numbers) {
        List<Integer> numsList = Arrays.stream(numbers).boxed().collect(Collectors.toList());

        List<List<Integer>> numsByOddity = new ArrayList<List<Integer>>();
        numsByOddity.add(new ArrayList<>()); // List of odd numbers
        numsByOddity.add(new ArrayList<>()); // List of even numbers

        numsList.forEach(num -> numsByOddity.get(num % 2).add(num));
        return numsByOddity;
    }

    private static void padShorterList(List<List<Integer>> numsByOddity) {
        int sizeDiff = numsByOddity.get(0).size() - numsByOddity.get(1).size();
        int listIndexToBePadded = sizeDiff < 0 ? 0 : 1;
        List<Integer> padding = Collections.nCopies(Math.abs(sizeDiff), 0);
        numsByOddity.get(listIndexToBePadded).addAll(padding);
    }

    private static List<Integer> joinLists(List<List<Integer>> numsByOddity) {
        List<Integer> resultList = new ArrayList<>(numsByOddity.get(1));
        for (int idx = 0; idx < numsByOddity.get(0).size(); idx++)
            resultList.add(idx * 2, numsByOddity.get(0).get(idx));
        return resultList;
    }
}

Complete code on GitHub

Hope this helps.

Using arrays something like this we can do. Code needs to be optimised.

    public static int[]  arrangeInEvenOddOrder(int[] arr)
    {
        // Create odd and even arrays
        int[] oddArr = new int[arr.length];
        int[] evenArr = new int[arr.length];
        int oCount = 0, eCount = 0;
        // populate arrays even and odd
        for (int i = 0; i < arr.length; i++) {
            if (arr[i] % 2 == 0)
                evenArr[eCount++] = arr[i];
            else
                oddArr[oCount++] = arr[i];
        }
        int[] resArr = new int[oCount >= eCount?
                               2*oCount :  2*eCount-1];
        // populate elements upto min of the
        // two arrays
        for (int i =0; i < (oCount <= eCount?
                2*oCount : 2*eCount ); i++ )
        {
            if( i%2 == 0)
                resArr[i] = evenArr[i/2];
            else
                resArr[i] = oddArr[i/2];
        }
        // populate rest of elements of max array
        // and add zeroes
        if (eCount > oCount)
        {
            for (int i=2*oCount,j=0;i<2*eCount-1; i++)
            {
                if (i%2 == 0)
                {
                    resArr[i] = evenArr[oCount+j];
                    j++;
                }
                else
                    resArr[i] = 0;
            }
        }
        else if (eCount < oCount)
        {
            for (int i=2*eCount,j=0;i<2*oCount; i++)
            {
                if ( i%2 != 0)
                {
                    resArr[i] = oddArr[eCount+j];
                    j++;
                }
                else
                    resArr[i] = 0;
            }
        }
        return resArr;
    }

Sort element based on index ie if the element is even, it must be at even position and vise-versa

 int sortArrayByEvenOddIndex(int arr[]) {
     int n = arr.length;
     int res[] = new int[n];
     int odd = 1;
     int even = 0;
    
     for (int i = 0; i < n; i++) {
         if (arr[i] % 2 == 0) {
             res[even] = arr[i];
             even += 2;
         } else {
             res[odd] = arr[i];
             odd += 2;
         }
     }
     return  res;
 }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM