Skip to content

Instantly share code, notes, and snippets.

@SamGerber-zz
Created April 27, 2016 21:24
Show Gist options
  • Save SamGerber-zz/5e396f2f6ba070146f452d4e46de8710 to your computer and use it in GitHub Desktop.
Save SamGerber-zz/5e396f2f6ba070146f452d4e46de8710 to your computer and use it in GitHub Desktop.
Given various ways to score points, represented by an arbitrary array w, count how many ways you can add up to a score s.
function waysToScore(awards, score, sorted = false) {
// Ensure the ways to score points are sorted.
if(!sorted) { awards.sort((a, b)=>( a - b )); }
var ways = new Array(score + 1).fill(0);
// There's one way to score 0 points
ways[0] = 1;
// Loop through each integer from 1 up to the score
for (var s = 1; s <= score; s++){
// Loop through the awards that are not greater than this score
for (var a = 0; a < awards.length && awards[a] <= s; a++){
// Calculate what the score must have been prior to award
let previousScore = ways[s - awards[a]];
// Add each of the ways of getting previousScore to current ways
ways[s] += previousScore;
}
}
// return the score (or 0 if it is still undefined)
return ways[score];
}
waysToScore([2, 3, 7, 8], 0, true); // 1
waysToScore([2, 3, 7, 8], 1, true); // 0
waysToScore([2, 3, 7, 8], 2, true); // 1
waysToScore([2, 3, 7, 8], 3, true); // 1
waysToScore([2, 3, 7, 8], 4, true); // 1
waysToScore([2, 3, 7, 8], 5, true); // 2
waysToScore([2, 3, 7, 8], 6, true); // 2
waysToScore([2, 3, 7, 8], 7, true); // 4
waysToScore([2, 3, 7, 8], 8, true); // 5
waysToScore([2, 3, 7, 8], 9, true); // 7
waysToScore([2, 3, 7, 8], 26, true); // 2687
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment