Skip to content

Instantly share code, notes, and snippets.

@sidhantpanda
Last active November 1, 2016 09:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save sidhantpanda/a5a26c2addfc3887f8ec8c32eca239d8 to your computer and use it in GitHub Desktop.
Save sidhantpanda/a5a26c2addfc3887f8ec8c32eca239d8 to your computer and use it in GitHub Desktop.
A bowling score calculator
// Assuming input is in form of [[1,2], [2,3], [10,0]]
// Came across this problem on the internet
// More at: https://blog.emilmoe.com/bowling-score-simulation/
module.exports = {
/**
* Return a list of accumulated result for an input array of scores in different throws
* @param Array attempts the attempts in the game
* @returns {Array} Score after each round, cummulatively
*/
calculateScore: function (attempts) {
var grandTotal = 0;
var totalScore = [];
for(var i=0; i<attempts.length; i++) {
if (isStrike(attempts[i])) {
grandTotal += getStrikeScore(attempts, i);
} else if (isSpare(attempts[i])) {
grandTotal += getSpareScore(attempts, i);
} else {
grandTotal += attempts[i][0] + attempts[i][1];
}
totalScore.push(grandTotal);
}
return totalScore;
}
};
function isStrike(attempt) {
return attempt[0] === 10;
}
function getStrikeScore(attempts, i) {
var total = 10; // initialize with this attempt's score
if (attempts[i+1] != null) {
if (isStrike(attempts[i+1])) {
total += 10; // add score of second strike
if (attempts[i+2] != null) {
total += attempts[i+2][0]; // add the third attempt's first throw irrespective of it being a strike
}
} else {
total += (attempts[i+1][0] + attempts[i+1][1]);
}
}
return total;
}
function isSpare(attempt) {
return attempt[0] < 10 && attempt[0] + attempt[1] === 10;
}
function getSpareScore(attempts, i) {
var total = 10; //initialize with spare score
if (attempts[i+1] != null) {
total += attempts[i+1][0];
}
return total;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment