没有sort()

时间:2018-01-03 13:42:17

标签: javascript sorting recursion combinations

我需要从123开头的结果,如下所示。我想从头开始打印sort()

  

1 2 3
  1 2 4
  1 2 5
  .....
  3 5 6
  4 5 6

但是,结果如下所示。

  

4 5 6
  3 5 6
  2 5 6
  1 5 6
  3 4 6
  2 4 6
  1 4 6
  2 3 6
  1 3 6
  1 2 6
  3 4 5
  2 4 5
  1 4 5
  2 3 5
  1 3 5
  1 2 5
  2 3 4
  1 3 4
  1 2 4
  1 2 3

result = "";
var N = 6;
var M = 3;
var arr = new Array(M);
combi(N, M, arr, M);
alert(result);

function combi(n, r, arr, sz) {
    var i = n + 1;
    while (i-- > r) {
        // choose the first element 
        arr[r - 1] = i;
        if (r > 1) { // if still needs to choose 
            // recursive into smaller problem 
            combi(i - 1, r - 1, arr, sz);
        } else {
            // print out one solution 
            var j = -1;
            while (++j < sz) {
                result += arr[j] + " ";
            }
            result += "\n";
        }
    }
}

2 个答案:

答案 0 :(得分:4)

除了所有的反转之外,你可以从一个和iterat开始直到想要的值。

function combination(n, r) {

    function iter(i, temp) {
        if (temp.length === r) {           // set complete
            result.push(temp.join(' '));   // join values
            return;
        }
        if (i + r > n + 1 + temp.length) { // exit early 
            return;
        }
        iter(i + 1, temp.concat(i));       // take the value
        iter(i + 1, temp);                 // go without the value
    }

    var result = [];                       // result set
    iter(1, []);                           // start with 1 and
    return result;                         // empty array for collecting sets
}

console.log(combination(6, 3));
.as-console-wrapper { max-height: 100% !important; top: 0; }

答案 1 :(得分:2)

您可以通过以下方式更改代码来恢复订单:

function combi(n, r, arr, sz) {
  var i = r - 1;
  while (i++ < n) {
    // choose the first element 
    arr[r - 1] = i;
    if (r > 1) { // if still needs to choose 
      // recursive into smaller problem 
      combi(i - 1, r - 1, arr, sz);
    } else {
      // print out one solution 
      var j = -1;
      while (++j < sz) {
        result += arr[j] + " ";
      }
      result += "\n";
    }
  }
}