Java将偶数元素分配给偶数索引,将奇数元素分配给奇数位置,并且如果数字不相等,则将零添加到这些位置

s4n0splo  于 2023-02-02  发布在  Java
关注(0)|答案(3)|浏览(163)

我试图写代码来显示偶数元素到偶数索引和奇数到奇数索引,如果数字添加的数字是相同的,然后相应地添加零。
示例:
x =[1,2,3,4]输出:2 1 4 3 x =[1 1 1 4]输出:4 1 0 1 0 1
我伸手去拿偶数和奇数的位置,但在那之后就卡住了。
下面是我的代码。

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] + "  ");
        }
    }

}
djp7away

djp7away1#

你可以把你的问题分解成3个部分:
1.首先创建两个列表,一个列表按遇到的顺序包含偶数,另一个列表包含奇数:

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.用零(0 s)填充两个列表中较短的一个,使其长度与另一个相等:

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.最后,将这两个列表交织在一起:

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;
    }

以下是完整的工作示例:

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

dfty9e19

dfty9e192#

使用数组我们可以做这样的事情,代码需要优化。

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;
    }
cpjpxq1n

cpjpxq1n3#

根据索引对元素排序,即如果元素是偶数,则必须位于偶数位置,反之亦然

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;
 }

相关问题