## The challenge

Given a list lst and a number N, create a new list that contains each number of lst at most N times without reordering. For example if N = 2, and the input is [1,2,3,1,2,1,2,3], you take [1,2,3,1,2], drop the next [1,2] since this would lead to 1 and 2 being in the result 3 times, and then take 3, which leads to [1,2,3,1,2,3].

Examples

 ``````1 2 3 4 5 `````` ``````// return [20,37,21] EnoughIsEnough.deleteNth(new int[] {20,37,20,21}, 1) // return [1, 1, 3, 3, 7, 2, 2, 2] EnoughIsEnough.deleteNth(new int[] {1,1,3,3,7,2,2,2,2}, 3) ``````

## The solution in Java code

Option 1:

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 `````` ``````import java.util.Arrays; import java.util.HashMap; public class EnoughIsEnough { public static int[] deleteNth(int[] elements, int maxOcurrences) { HashMap map = new HashMap<>(); return Arrays.stream(elements) .filter(i -> { map.merge(i, 1, Integer::sum); return map.get(i) <= maxOcurrences; }) .toArray(); } } ``````

Option 2:

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 `````` ``````import java.util.*; public class EnoughIsEnough { public static int[] deleteNth(int[] elements, int maxOcurrences) { if (elements == null || elements.length == 0) return new int[0]; Map numberCount = new HashMap<>(); List filteredList = new ArrayList<>(); for (Integer aNumber : elements) { if (numberCount.containsKey(aNumber)) numberCount.put(aNumber, numberCount.get(aNumber)+1); else numberCount.put(aNumber, 1); if (numberCount.get(aNumber) <= maxOcurrences) filteredList.add(aNumber); } return filteredList.stream().mapToInt(Integer::valueOf).toArray(); } } ``````

Option 3:

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 `````` ``````import java.util.Collections; import java.util.stream.IntStream; import java.util.ArrayList; import java.util.List; public class EnoughIsEnough { public static int[] deleteNth(int[] ar, int max) { List list = new ArrayList<>(); for (int n : ar) if (Collections.frequency(list, n) < max) list.add(n); return list.stream().mapToInt(Integer::intValue).toArray(); } } ``````

## Test cases to validate our solution

 `````` 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 `````` ``````import org.junit.jupiter.api.Test; import static org.junit.jupiter.api.Assertions.*; class EnoughIsEnoughTest { @Test public void deleteNth() throws Exception { assertArrayEquals( new int[] { 20, 37, 21 }, EnoughIsEnough.deleteNth( new int[] { 20, 37, 20, 21 }, 1 ) ); assertArrayEquals( new int[] { 1, 1, 3, 3, 7, 2, 2, 2 }, EnoughIsEnough.deleteNth( new int[] { 1, 1, 3, 3, 7, 2, 2, 2, 2 }, 3 ) ); assertArrayEquals( new int[] { 1, 2, 3, 1, 1, 2, 2, 3, 3, 4, 5 }, EnoughIsEnough.deleteNth( new int[] { 1, 2, 3, 1, 1, 2, 1, 2, 3, 3, 2, 4, 5, 3, 1 }, 3 ) ); assertArrayEquals( new int[] { 1, 1, 1, 1, 1 }, EnoughIsEnough.deleteNth( new int[] { 1, 1, 1, 1, 1 }, 5 ) ); assertArrayEquals( new int[] { }, EnoughIsEnough.deleteNth( new int[] { }, 5 ) ); } } ``````