Copulation of negative elements in the mass



  • It is necessary to write a code copying one set in another as follows: first, all components, large 0, then all components, equal 0, and then all components, lower 0, are copied in sequence. How do you do that? This is my failed attempt to accomplish this task:

            int[] arr = new int[100];
            Random random = new Random();
    
        for (int i = 0; i < arr.length; i++)
        {
            int randNum = random.nextInt(800) - 400;
            arr[i] = randNum;
        }
        int[] newArr = new int[100];
        int[] positive = new int[100];
        int[] negative = new int[100];
        int[] zerro = new int[100];
        int count = 0;
        for (int j = 0; j < arr.length; j++)
        {
            if (arr[j] > 0)
            {
                positive[j] = arr[j];
                // System.arraycopy(arr, arr[j], newArr, 0, 100); Not works!
            }
            if (arr[j] == 0)
            {
                zerro[j] = arr[j];
            }
            if (arr[j] < 0)
            {
                negative[j] = arr[j];
            }
        }
        System.arraycopy(positive, 0, negative, 0, 100);   // Not works!
        System.out.println(Arrays.toString(arr));
        System.out.println(Arrays.toString(positive));
        System.out.println(Arrays.toString(zerro));
        System.out.println(Arrays.toString(negative));
    

    // System.out.println(Arrays.toString(newArr));



  • This requires the establishment of an interface (version) Comparator<Integer> and redesign the method compare:

    private class CustomComparator implements Comparator<Integer> {
    
        @Override
        public int compare(Integer o1, Integer o2) {
            if (o1 &gt; 0 &amp; o2 != 0) {
                return o1 - o2;
            }
            if (o1 &gt; 0 &amp; o2 == 0) {
                return -1;
            }
            if (o1 &lt; 0 &amp; o2 &lt; 0) {
                return o2 - o1;
            }
            if (o1 &lt; 0 &amp; o2 &gt;= 0) {
                return 1;
            }
            if (o1 == 0) {
                return o2;
            }
            return 0;
        }
    

    And then use it at his discretion. For example:

    CustomComparator customComparator = new CustomComparator();
    List<Integer> sortedList = Stream.of(12, 1, 3, 4, 5, 0, 18, 0, -123, -22, -23).sorted(customComparator).collect(Collectors.toList());




Suggested Topics

  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2
  • 2