Javascript给出了一个数字我想要所有可能的组合和元素数组

时间:2015-02-12 12:53:22

标签: javascript algorithm search combinations

在javascript代码中,我将所有可能的元素组合,其总和给出我想要的数字: 例如:

array = [2, 1, 2, 1]; 
number = 3; 
finalArray = [[2, 1], [2, 1], [1, 2], [2, 1]]

array = [5, 5, 4, 4, 2] 
number = 10 
finalArray = [[5, 5], [4, 4, 2]]

这是我的代码,但我只有第一个组合!我不知道为什么当我返回递归函数时,返回主函数并且它不会继续另一个组合。 你能帮我吗?我按照Finding all possible combinations of numbers to reach a given sum

进行操作
 $(document).ready(function() {

    var numero = 3;
    var array = [2, 1, 2, 1];
    var tmpArray = [];
    var finalArray = [];

    $("#button").click(function() {
        combinationTableCard(array, numero, tmpArray);
        console.log(finalArray);
    })

    function combinationTableCard(cardArray, number, partialArray) {

            var n;
            var s = sumArray(partialArray);
            if (s == number) {
                finalArray.push(partialArray);
            }
            if (s >= number) {
                return;
            }
            for (i=0; i<cardArray.length; i++) {
                    n = cardArray[i];
                    var remaining = copyArray(cardArray, i+1, cardArray.length-1);

                    partialArray.push(n);
                    combinationTableCard(remaining, number, partialArray);
            }
        }

    function sumArray(v) {
            var total = 0;      
            if (v.length == 0) {
                return total;
            } else {
                for (i=0; i<v.length; i++) {
                    total += v[i];
                }
                return total;
            }
        }

        function copyArray(v, i, j) {
            var newV = new Array();
            var k = 0;
            for(i; i <= j; i++) {
                newV[k] = v[i];
                k++;
            }
            return newV;
        }

    })

2 个答案:

答案 0 :(得分:2)

在这个函数中,问题是你没有将i声明为局部变量,所以它变成了全局变量.function combinationTableCard和sumArray使用相同的变量i。声明var i;你会得到理想的结果。

答案 1 :(得分:0)

你走了。仍然需要做一些展示工作

   <!DOCTYPE html>

    <head>
      <meta charset="utf-8">
       <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
      <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css">
      <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/smoothness/jquery-ui.css">
      <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/jquery-ui.min.js"></script>
      <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/font-awesome/4.3.0/css/font-awesome.min.css">

      <style>
      body {background-color:lightgray}
      </style>
    </head>
    <body>
      <div id="container"></div>
      <button type="button" id="button">Click Me To Calculate combination!</button>
      <script>
      $(document).ready(function() {

        var target = 15;
        var array = [3,9,8,4,5,7,10];
        var tmpArray = [];
        var finalArray = [];

        $("#button").click(function() {
          sum_up_recursive(array, target, tmpArray);
          console.log(finalArray.toString());
          var finalText = '';
          finalArray.forEach(function(entry) {
            finalText = finalText + entry + '</br>';
          });
          $("#container").html(finalText);
        })

        function sum_up_recursive(numbers, number, partialArray) {

          var s=0;
          partialArray.forEach(function(entry) {
            s=s+entry;
          });
          if (s == target) {
            //finalArray.push(partialArray);
            var res = partialArray.join();  
            res=res.replace(/,/g , '+');
            res= res+"="+s;
             console.log(res);
             finalArray.push(partialArray);
            //$("#container").text(res);
          }
          if (s >= target) {
            return;
          }
          for (var i=0; i<numbers.length; i++) {
            n = numbers[i];
            //var remaining = copyArray(cardArray, i+1, cardArray.length-1);
            var remaining = [];
            var remaining = numbers.slice(i+1);
            var partical_arr = partialArray.slice();       
            partical_arr.push(n);
            sum_up_recursive(remaining, target, partical_arr);
          }
        }

      });

      </script>

    </body>
    </html>