Last active
March 4, 2020 01:02
-
-
Save javi-aire/9dbc188de39b5d6107089a44890b92de to your computer and use it in GitHub Desktop.
solution to this challenge: https://www.reddit.com/r/dailyprogrammer/comments/dv0231/20191111_challenge_381_easy_yahtzee_upper_section/?utm_source=share&utm_medium=web2x
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
/** | |
* | |
* 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