Delete Occurrences of an Element if it occurs more than N times in Java

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

// 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)
Code language: JavaScript (javascript)

The solution in Java code

Option 1:

import java.util.Arrays; import java.util.HashMap; public class EnoughIsEnough { public static int[] deleteNth(int[] elements, int maxOcurrences) { HashMap<Integer, Integer> map = new HashMap<>(); return Arrays.stream(elements) .filter(i -> { map.merge(i, 1, Integer::sum); return map.get(i) <= maxOcurrences; }) .toArray(); } }
Code language: Java (java)

Option 2:

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<Integer, Integer> numberCount = new HashMap<>(); List<Integer> 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(); } }
Code language: Java (java)

Option 3:

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<Integer> list = new ArrayList<>(); for (int n : ar) if (Collections.frequency(list, n) < max) list.add(n); return list.stream().mapToInt(Integer::intValue).toArray(); } }
Code language: Java (java)

Test cases to validate our solution

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 ) ); } }
Code language: Java (java)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments