Permutations & Combinations
HTML
<h1>Permutations and Combinations</h1>
<p>This code shows how to calculate permutations, combinations and permutations with repititions. <br />
Let's assume n = 10 and r = 4. <br />
The rules are:
<p class="rule">
<em>n<sup>r</sup></em> which will be 10x10x10x10
</p>
<p class="rule">
<em><sup>n</sup>P<sub>r</sub> = n!/(n-r)! </em> which will be 10!/6!
</p>
<p class="rule">
<em><sup>n</sup>C<sub>r</sub> = n!/r!(n-r)! </em> which will be 10!/4!6!
</p>
</p>
<label>Number of Characters you have (n): <input type="text" id="n" /></label>
<label>Number of slots you have (r): <input type="text" id="r" /></label>
<button>Calculate</button>
<div id="results">Permutation with Repitition <em>n<sup>r</sup></em>: <span></span>
<p>e.g. Passwords with certain number of chars/digits (n) in a certain number of slots (r)</p>
</div>
<div id="premutation">Permutation with No Repitition <em><sup>n</sup>P<sub>r</sub></em>: <span></span>
</div>
<div id="combination">Combination <em><sup>n</sup>C<sub>r</sub></em>: <span></span></div>
CSS
body{font-family:arial; font-size:0.9em;padding:0.4em;}
h1 {font-weight:bold;margin:1em 0;}
label {clear:left; float:left; margin-top:10px; width:70%;}
input {float:right; width:50px;}
button {clear:both; float:left;}
em {font-style:italic; font-weight:bold;}
div {clear:both; float:left; padding-bottom:10px; border-bottom:1px solid #ccc; width:100%;}
p{font-size:0.78em;}
.rule {background-color:#f06;padding:5px;}
.rule em {font-size:1.1em;}
JavaScript
function factorial(n) {
var result, i;
result = 1;
for (i = 1; i <= n; i++) {
//alert(result + ' ' + i);
result = result * i;
}
return result;
}
function expont(x, y) {
var i = 0;
var result = 1;
for (i = 0; i < y; i++) {
result = result * x;
// alert('i: '+i+' result: '+result);
}
return result;
}
$('button').click(function() {
var n = $('#n').val();
var r = $('#r').val();
if (n===""){n = 0;}
if (r===""){r = 0;}
var w = expont(n, r);
var p = factorial(n) / factorial(n - r);
var c = factorial(n) / (factorial(n - r) * factorial(r));
$('#results span').text(w);
$('#premutation span').text(p);
$('#combination span').text(c);
$('#results em').html(n+'<sup>'+r+'</sup>');
$('#premutation sup, #combination sup').text(n);
$('#premutation sub, #combination sub').text(r);
//alert(q);
});