function combination(n,k){
return factorial(n)/(factorial(k) + factorial(n-k);
}
function factorial(n){
nf = 1;
for (i=1;i<=n;i++){
nf = nf*i;
}
return nf;
}
I'm looking for something more like:
def combination (n,k)
f = lambda {|x|(1..x).inject(1){|x,y|x*y}}
result f(n)/(f(k)*f(n-k))
end
If anyone can use array.reduce in Javascript without it turning into a mess, I would like to know. <_<
4 comments:
I think most developers will prefer the first one anyway. I would rewrite factorial to be recursive with memoization though. (http://en.wikipedia.org/wiki/Memoization) The combination function should also be "memoized".
I think that'd be the cleanest.
I read the first 140 characters; are you suggesting I have a hash table of factorial values?
But the second one is saving me so much screen space!
On second thought, storing the previous computations of the factorials is overkill.
Post a Comment