Score dice pairs
A dice game awards points from matching pairs. For each face value that appears more than once, every pair of matching dice contributes the face value to the total score.
- Count how many times each face value appears.
- A face appearing k times forms k*(k-1)/2 pairs.
- Each pair scores the face value.
- If no value repeats, the score is zero.
dicePairsScore(dice: list<int>) → 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
int dicePairsScore(List<Integer> dice) {
}
Worked examples
| Call | Result |
|---|---|
dicePairsScore(Main.<Integer>ls(2, 3, 2, 5, 3)) | 5 |
dicePairsScore(Main.<Integer>ls(6, 6, 6)) | 18 |
dicePairsScore(Main.<Integer>ls(1, 2, 3)) | 0 |
dicePairsScore(Main.<Integer>ls(4, 4, 4, 4)) | 24 |
Hint
Count frequencies, then for each face with two or more occurrences add value * count * (count - 1) / 2.
Reference solution in Java
int dicePairsScore(List<Integer> dice) {
Map<Integer, Integer> freq = new HashMap<>();
for (int d : dice) freq.put(d, freq.getOrDefault(d, 0) + 1);
int sum = 0;
for (var e : freq.entrySet()) {
int k = e.getValue();
if (k >= 2) sum += e.getKey() * k * (k - 1) / 2;
}
return sum;
}