Skip to content

Instantly share code, notes, and snippets.

@javi-aire
Last active March 4, 2020 01:02
Show Gist options
  • Save javi-aire/9dbc188de39b5d6107089a44890b92de to your computer and use it in GitHub Desktop.
Save javi-aire/9dbc188de39b5d6107089a44890b92de to your computer and use it in GitHub Desktop.
/**
*
* Given a dice roll result in Yahtzee (input as an array of 5 integers 1-6),
* find the maximum possible score for that roll.
*
* Yahtzee Scoring Rules
* ---------------------
* 1 * numberOfOnes
* 2 * numOFTwos
* 3 * numOfThrees
* 4 * numOfFours
* 5 * numOfFives
* 6 * numOfSixes
*
* Ex. [2, 3, 5, 5, 6] would result in each number being [0, 2, 3, 0, 10, 6],
* and the number to return would be 10
*/
function upperSectionScore(diceResult){
// handle empty array
if(diceResult.length === 0){
return -1;
}
// will need a way to count the frequency of each number
// a variable to store/return the value, and store the largest num freq
let frequency = {
'1': 0,
'2': 0,
'3': 0,
'4': 0,
'5': 0,
'6': 0
},
score = 1;
// TODO:
// 1) loop thru each roll, counting the frequency of each number rolled
// 2) find the largestFreqNum num
// 3) using the largestFreqNum, calculate the value and return the score.
diceResult.reduce((acc, roll, idx) => {
// 1)
frequency[roll] += 1;
let numToCompare = diceResult[idx];
// 2)
if(frequency[acc] <= frequency[numToCompare]){
acc = numToCompare;
}
// 3)
score = acc * frequency[acc];
return acc;
}, score);
return score;
}
console.log(upperSectionScore([2, 3, 5, 5, 6])); // 10
console.log(upperSectionScore([1, 1, 1, 1, 1])); // 5
console.log(upperSectionScore([])); // -1
console.log(upperSectionScore([2, 4, 3, 4, 4])); // 12
console.log(upperSectionScore([6, 6, 6, 6, 6])); // 30
console.log(upperSectionScore([1, 1, 3, 2, 3])); // 6
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment