Thursday, September 21, 2023
HomeSoftware EngineeringThe right way to Resolve Max-Min Arrays in Java

The right way to Resolve Max-Min Arrays in Java


The problem

You’re given an array of distinctive parts, and your job is to rearrange the values in order that the primary max worth is adopted by the primary minimal, adopted by second max worth then second min worth, and so on.

For instance:

clear up([15,11,10,7,12]) = [15,7,12,10,11]

The primary max is 15 and the primary min is 7. The second max is 12 and the second min is 10 and so forth.

The answer in Java code

Choice 1:

import java.util.*;

class Answer{
    public static int[] clear up (int[] arr){  
        Arrays.kind(arr);
        int[] solutionArray = new int[arr.length];
        
        for(int i = 0; i < arr.size; i++){
          solutionArray[i] = i % 2 == 0 ? arr[arr.length - i/2 - 1] : arr[i/2];
        }
        return solutionArray;
    }
}

Choice 2:

import java.util.*;

class Answer{
    public static int[] clear up (int[] arr){  
        Listing<Integer> temp = new ArrayList<Integer>(); 
        Arrays.kind(arr);
        for (int i = 0, j = arr.size - 1; i <= j; ++i, --j) {
            if (i != j) temp.add(arr[j]);
            temp.add(arr[i]);
        }
        return temp.stream().mapToInt(i -> i).toArray(); 
    }
}

Choice 3:

import java.util.stream.IntStream;

class Answer {

  public static int[] clear up(int[] arr) {
    int[] sorted = IntStream.of(arr).sorted().toArray();
    int[] consequence = new int[arr.length];
    for (int i = 0, j = arr.size - 1, f = -1; i < arr.size;) {
      consequence[i] = sorted[j];
      j = (j + arr.size + (f *= -1) * (++i)) % arr.size;
    }
    return consequence;
  }

}

Take a look at circumstances to validate our answer

import org.junit.Take a look at;
import static org.junit.Assert.assertArrayEquals;
import org.junit.runners.JUnit4;

public class SolutionTest{    
    @Take a look at
    public void basicTests(){     
        assertArrayEquals(new int[]{15,7,12,10,11},Answer.clear up(new int[]{15,11,10,7,12}));
        assertArrayEquals(new int[]{15,7,12,10,11},Answer.clear up(new int[]{15,11,10,7,12}));
        assertArrayEquals(new int[]{15,7,12,10,11},Answer.clear up(new int[]{15,11,10,7,12}));    
    }
}
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments