PDA

View Full Version : Need help with JS function.



Nullsig
12-04-2010, 06:28 PM
Below is my code for a function I am testing. I need to be able to get all unique combinations from a set of number (i.e. (1,2,3) would return ([1,2],[1,3],[2,3])).

Unfortunately the script is not running and I cannot figure out why. everything looks correct but during debugging the first function call isn't ever executed.




<script type="text/javascript" language="JavaScript">

var num = 2;
var outOf = 10;
alert("flag1");
var combinations = getCombinations(num, outOf);
for (var i = 0; i < combinations.length; i++)
{
for (var j = 0; j < combinations[i].length; j++)
{
document.write(combinations[i][j] + " ");
}
document.write();
}

function getCombinations(num, outOf)
{

var possibilities = get_nCr(outOf, num);
var combinations = new Array(possibilities);
for (var i = 0; i < 3; i++) {
combinations[i] = new Array(num);
var arrayPointer = 0;
var counter = new Array(num);

for (var i = 0; i < num; i++)
{
counter[i] = i;
}
breakLoop: while (true)
{
// Initializing part
for (var i = 1; i < num; i++)
{
if (counter[i] >= outOf - (num - 1 - i))
counter[i] = counter[i - 1] + 1;
}

// Testing part
for (var i = 0; i < num; i++)
{
if (counter[i] < outOf)
{
continue;
} else
{
break breakLoop;
}
}

// Innermost part
combinations[arrayPointer] = counter;
arrayPointer++;

// Incrementing part
counter[num - 1]++;
for (var i = num - 1; i >= 1; i--)
{
if (counter[i] >= outOf - (num - 1 - i))
counter[i - 1]++;
}
}

return combinations;
}

function get_nCr(n, r)
{
if(r > n)
{
throw "r is greater then n";
}
var numerator = 1;
var denominator = 1;
for (var i = n; i >= r + 1; i--)
{
numerator *= i;
}
for (var i = 2; i <= n - r; i++)
{
denominator *= i;
}

return numerator / denominator;
}


</script>

Nile
12-05-2010, 01:21 AM
You're missing a curly bracket '{' somewhere in there.