Created
March 26, 2020 04:43
-
-
Save RP-3/6da390811b396b66a9464b9192512c1b to your computer and use it in GitHub Desktop.
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
// Memoized Recursive | |
// O(d*t) | |
// Unmemoized would be O((d*t)*f^d). I.e., recursive fn with branch factor f and max depth d | |
var numRollsToTarget = function(d, f, target) { | |
const memo = {}; | |
const mod = Math.pow(10, 9) + 7; | |
const rtt = (d, t) => { | |
if(t <= 0 || // no dice scores will ever be zero or less | |
d <= 0 || // and the question makes no sense with zero or fewer dice | |
t < d || // also, the min score for each die is 1, so t cannot be < d | |
t > d*f // also t cannot exceed the max allowable score | |
) return 0; // in all such cases, return 0 | |
if(d === 1) return t<=f ? 1 : 0; // if there's only one dice, there can only be one or zero ways | |
const key = `${d}:${t}`; | |
if(memo[key]) return memo[key]; | |
let result = 0; | |
for(let i=1; i<=f; i++) // for all possible scores for this one die | |
result = (result + rtt(d-1, t-i)) % mod; // figure out the result for d-1 dice | |
return memo[key] = result % mod; | |
}; | |
return rtt(d, target); | |
}; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment