Bucket some readings
A chart needs counts per band rather than raw readings — how many orders fell between 0 and 9, 10 and 19, and so on.
- Readings are never negative.
- A bucket is named by the value it starts at, written as a string: "0", "10", "20".
- Buckets with nothing in them do not appear.
- A bucket size of zero or less gives an empty result.
histogram(values: list<int>, bucketSize: int) → map<string, int>
Java needs a compiler and Drill does not host one yet, so this page is the reference rather than an exercise: the problem, worked examples, and the solution in full. To type it out, the same problem runs in Python.
Where you start
Map<String, Integer> histogram(List<Integer> values, int bucketSize) {
}
Worked examples
| Call | Result |
|---|---|
histogram(Main.<Integer>ls(0, 5, 10, 15, 23), 10) | Main.<String, Integer>mp("0", 2, "10", 2, "20", 1) |
histogram(Main.<Integer>ls(9, 10), 10) | Main.<String, Integer>mp("0", 1, "10", 1) |
histogram(Main.<Integer>ls(1, 2, 3), 1) | Main.<String, Integer>mp("1", 1, "2", 1, "3", 1) |
histogram(Main.<Integer>ls(1, 2), 0) | Main.<String, Integer>mp() |
Hint
Integer-divide by the bucket size, multiply back, and that is the bucket name.
Reference solution in Java
Map<String, Integer> histogram(List<Integer> values, int bucketSize) {
Map<String, Integer> result = new LinkedHashMap<>();
if (bucketSize <= 0) return result;
for (int v : values) {
String k = String.valueOf((v / bucketSize) * bucketSize);
result.merge(k, 1, Integer::sum);
}
return result;
}