English 中文(简体)
最有效的方式是撰写 Java版的合并和变换计算器
原标题:Most efficient way to write Combination and Permutation calculator in Javascript
  • 时间:2011-10-12 16:01:07
  •  标签:
  • javascript

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 permutations in Javascript. Live calculator is at http://finitehelp.com/finite-calculator.html. I know next to nothing about Javascript and would venture to guess there is a much more efficient way to write the following particularly because of the excessive use of variables. If someone could please help me I would be very grateful.

<script type="text/javascript">
// calculate n!
Math.factorial = function(n)
{
    if(typeof n ==  string ) n = Number(n);
    if(typeof n !=  number  || isNaN(n))
    {
        alert("Factorial requires a numeric argument.");
        return null;
    }
    if (n < 2) return 1;
    return (n * Math.factorial(n-1));
}
Math.divide = function(a,b)
{
    return a/b;
}
</script>

<form class="form" name="combination" action="">
    <p>C(<input type="text" value="n" name="T1" size="1">,<input type="text" value="r" name="T2" size="1">)
    <input type="button" value="Calculate"
     onclick="var n = T1.value; var r = T2.value; var n_minus_r = parseFloat(n) - parseFloat(r); var numerator = Math.factorial(T1.value); var n_minus_r_fact = Math.factorial(n_minus_r); var r_fact = Math.factorial(r); var denominator = n_minus_r_fact * r_fact; T3.value = Math.divide(numerator,denominator); return true;">
    = <input type="text" name="T3" size="12" readonly></p>
</form>
最佳回答

在这里,我们走了!

首先,你为什么需要写这句话?

Math.divide = function(a,b)
{
    return a/b;
}

我会完全放弃。

您也可清理<条码>。 a 略微:

Math.factorial = function(n)
{
    n = Number(n);

    if (isNAN(n)) {
        alert("Factorial requires a numeric argument.");
        return null;
    } else if (n < 2) {
        return 1;
    } else {
        return (n * Math.factorial(n - 1));
    }
}

但主要问题是:<条码>():

onclick="var n = T1.value; var r = T2.value; var n_minus_r = parseFloat(n) - parseFloat(r); var numerator = Math.factorial(T1.value); var n_minus_r_fact = Math.factorial(n_minus_r); var r_fact = Math.factorial(r); var denominator = n_minus_r_fact * r_fact; T3.value = Math.divide(numerator,denominator); return true;

页: 1 d) 使它成为一种功能,并使它与这个要素相联,从而在你的超文本中消除所有强奸行为,使之更容易与以下方面合作:

window.onload = function()
{
    document.getElementById( calculate ).onclick = function() {
        var n = T1.value,
            r = T2.value;

        T3.value = Math.factorial(n) / (Math.factorial(r) * Math.factorial(n - r));
    }
}

仅删除<代码>onclick=。

问题回答

If you re concerned about efficiency, you d probably want to re-implement the factorial as an iterative function rather than a recursive one. The recursive version will use a lot more memory and CPU time than the iterative version.

function factorial(n) { 
  var x=1; 
  var f=1;
  while (x<=n) {
    f*=x; x++;
  }
    return f;
}

You also shouldn t be adding your own functions to the Math namespace. It s not a good habit to get into.

As we know, combinations is short for(https://en.wikipedia.org/wiki/Combination):

enter image description here

So the fastest combinations implement is below(only if n is small):

// r*(r-1)*...*2*1
function factorial(r) {
  let s = 1;
  while (r > 1) s *= r--;
  return s;
}

function combinations(n,r){
    let s = 1;
    let i = r;
    // n*(n-1)*....*(n-r+1)
    while(i<n) s*=++i;
    return s/factorial(n-r)
}
console.log(combinations(100,2) === 4950) // false

Note: math float operation has Precision limit, for example combinations(100,2)==4950 is false. But https://www.wolframalpha.com/input?i=100+choose+2 tells us it s true result is 4950.

因此,我们应当使用<条码>BigInt取代<条码>float 业务:

// r*(r-1)*...*2*1
function factorial(r) {
    let s = BigInt(1);
    var i = BigInt(r)
    while (i > 1) s *= i--;
    return s;
}

// n*(n-1)*....*(n-r+1) / factorial(r)
function combinations(n, r){
    let s = BigInt(1);
    let i = BigInt(r);
    while(i<n) s*=++i;
    return s/factorial(n-r)
}
console.log(combinations(100,2) === 4950n) // true

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

我更喜欢休养功能,尾补假可能会造成诸如菲博托等职能的停滞。

Math._factorial = function(n){
  return Math._fact(n,1);
}

Math._fact= function(n,res){
  n = Number(n);
  if (n == null) {
    alert("Factorial requires a numeric argument.");
    return null;
  } else if (n < 2){
    return res;
  } else {
    return Math._fact(n-1, res*n);
  }
}




相关问题
selected text in iframe

How to get a selected text inside a iframe. I my page i m having a iframe which is editable true. So how can i get the selected text in that iframe.

How to fire event handlers on the link using javascript

I would like to click a link in my page using javascript. I would like to Fire event handlers on the link without navigating. How can this be done? This has to work both in firefox and Internet ...

How to Add script codes before the </body> tag ASP.NET

Heres the problem, In Masterpage, the google analytics code were pasted before the end of body tag. In ASPX page, I need to generate a script (google addItem tracker) using codebehind ClientScript ...

Clipboard access using Javascript - sans Flash?

Is there a reliable way to access the client machine s clipboard using Javascript? I continue to run into permissions issues when attempting to do this. How does Google Docs do this? Do they use ...

javascript debugging question

I have a large javascript which I didn t write but I need to use it and I m slowely going trough it trying to figure out what does it do and how, I m using alert to print out what it does but now I ...

Parsing date like twitter

I ve made a little forum and I want parse the date on newest posts like twitter, you know "posted 40 minutes ago ","posted 1 hour ago"... What s the best way ? Thanx.

热门标签