Last active
October 2, 2020 16:41
-
-
Save press0/394bff48460c0f2e295bcc1976cbbeaf to your computer and use it in GitHub Desktop.
functional array update 'in place'; in 2 passes; order by 3,1,2; no other values
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import static java.util.stream.Collectors.counting; | |
import static org.junit.Assert.assertArrayEquals; | |
import java.util.Arrays; | |
import java.util.Map; | |
import java.util.function.Function; | |
import java.util.stream.Collectors; | |
import java.util.stream.IntStream; | |
import org.junit.Test; | |
/** | |
* update array 'in place'; order by 3,1,2; no other values; in only 2 passes | |
* | |
* | |
*/ | |
public class GH312SortTest { | |
public static void sortIt(int[] arr) { | |
//read array | |
Map<Integer, Long> map = | |
Arrays.stream(arr).boxed().collect(Collectors.toList()).stream().collect( | |
Collectors.groupingBy( | |
Function.identity(), counting() | |
) | |
); | |
int x1 = map.getOrDefault(1, 0L).intValue(); | |
int x3 = map.getOrDefault(3, 0L).intValue(); | |
//update array in place | |
IntStream.range(0, x3).forEach(i -> arr[i] = 3); | |
IntStream.range(x3, x3 + x1).forEach(i -> arr[i] = 1); | |
IntStream.range(x3 + x1, arr.length).forEach(i -> arr[i] = 2); | |
} | |
@Test | |
public void test() { | |
int[] arr = new int[]{}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{}, arr); | |
} | |
@Test | |
public void test1a() { | |
int[] arr = new int[]{1}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{1}, arr); | |
} | |
@Test | |
public void test1b() { | |
int[] arr = new int[]{2}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{2}, arr); | |
} | |
@Test | |
public void test2a() { | |
int[] arr = new int[]{1,3}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{3,1}, arr); | |
} | |
@Test | |
public void test3a() { | |
int[] arr = new int[]{2, 2, 2, 3, 1, 1, 1, 1, 2, 3}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{3, 3, 1, 1, 1, 1, 2, 2, 2, 2}, arr); | |
} | |
@Test | |
public void test3b() { | |
int[] arr = new int[]{2, 2, 2, 2, 2, 2, 1, 1, 2, 2}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{1,1,2,2,2,2,2,2,2,2}, arr); | |
} | |
@Test | |
public void test3c() { | |
int[] arr = new int[]{2, 1, 3, 2, 1, 3, 2, 1, 3}; | |
GH312SortTest.sortIt(arr); | |
assertArrayEquals(new int[]{3,3,3,1,1,1,2,2,2}, arr); | |
} | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment