Results 1 to 2 of 2

Thread: Need help with JS function.

  1. #1
    Join Date
    Dec 2010
    Posts
    1
    Thanks
    0
    Thanked 0 Times in 0 Posts

    Default Need help with JS function.

    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>

  2. #2
    Join Date
    Jan 2008
    Posts
    4,168
    Thanks
    28
    Thanked 628 Times in 624 Posts
    Blog Entries
    1

    Default

    You're missing a curly bracket '{' somewhere in there.
    Jeremy | jfein.net

Bookmarks

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •