The problem
Given an inventory lst and a quantity N, create a brand new listing that accommodates every variety of lst at most N instances with out reordering. For instance if N = 2, and the enter is [1,2,3,1,2,1,2,3], you are taking [1,2,3,1,2], drop the subsequent [1,2] since this might result in 1 and a couple of being within the outcome 3 instances, after which take 3, which results in [1,2,3,1,2,3].
Instances
// 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 answer in Java code
Possibility 1:
import java.util.Arrays;
import java.util.HashMap;
public class EnoughIsEnough {
public static int[] deleteNth(int[] components, int maxOcurrences) {
HashMap<Integer, Integer> map = new HashMap<>();
return Arrays.stream(components)
.filter(i -> {
map.merge(i, 1, Integer::sum);
return map.get(i) <= maxOcurrences;
})
.toArray();
}
}
Possibility 2:
import java.util.*;
public class EnoughIsEnough {
public static int[] deleteNth(int[] components, int maxOcurrences) {
if (components == null || components.size == 0) return new int[0];
Map<Integer, Integer> numberCount = new HashMap<>();
Checklist<Integer> filteredList = new ArrayList<>();
for (Integer aNumber : components) {
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();
}
}
Possibility 3:
import java.util.Collections;
import java.util.stream.IntStream;
import java.util.ArrayList;
import java.util.Checklist;
public class EnoughIsEnough {
public static int[] deleteNth(int[] ar, int max) {
Checklist<Integer> listing = new ArrayList<>();
for (int n : ar)
if (Collections.frequency(listing, n) < max) listing.add(n);
return listing.stream().mapToInt(Integer::intValue).toArray();
}
}
Take a look at instances to validate our answer
import org.junit.jupiter.api.Take a look at;
import static org.junit.jupiter.api.Assertions.*;
class EnoughIsEnoughTest {
@Take a look at
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 )
);
}
}