Most efficient way to write Combination and Permutation calculator in Javascript

前端 未结 5 984
闹比i
闹比i 2021-01-12 10:05

I have a math website http://finitehelp.com that teaches students Finite Math. I thought it would be cool to include a calculator so I made one for combinations and permutat

5条回答
  •  误落风尘
    2021-01-12 11:05

    Math.factorial= function(n){
        var i= n;
        while(--i) n*= i;
        return n;
    }
    
    Math.combinations= function(n, r, repeats){
        if(n< r) return 0;
        if(n=== r) return 1;
        if(repeats){
            return Math.factorial(n+r-1)/((Math.factorial(r)*Math.factorial(n-1)));
        }
        return Math.factorial(n)/((Math.factorial(r)*Math.factorial(n-r)));
    }
    
    
    var a= [
        'aqua', 'black', 'blue', 'fuchsia', 'gray', 'green', 'lime', 'maroon',
        'navy', 'olive', 'orange', 'purple', 'red', 'silver', 'teal', 'white',
        'yellow'
    ]
    //how many 3 color combinations are there?
    //[red,green,blue] is different than [green,red,blue]
    // Math.combinations(a.length,3,true) >>969
    // how many unique combinations (ignoring order) are there?
    // Math.combinations(a.length,3)>>680
    

提交回复
热议问题