Drill

ProblemsJavaScript › games

Score dice pairs

hardgamesJavaScript

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.

dicePairsScore(dice: list<int>) → int

Solve it in the editor →

Where you start

function dicePairsScore(dice) {
  
}

Worked examples

CallResult
dicePairsScore([2,3,2,5,3])5
dicePairsScore([6,6,6])18
dicePairsScore([1,2,3])0
dicePairsScore([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 JavaScript
function dicePairsScore(dice) {
  const freq = {};
  for (const d of dice) freq[d] = (freq[d] || 0) + 1;
  let sum = 0;
  for (const v in freq) {
    const k = freq[v];
    if (k >= 2) sum += Number(v) * k * (k - 1) / 2;
  }
  return sum;
}

The same problem in another language

More games problems in JavaScript