如何在JavaScript数组中输出来自30个不同数字的7个数字的所有可能组合? [英] How would I output all the possible combination of 7 numbers from 30 different numbers in an array in Javascript?

查看:57
本文介绍了如何在JavaScript数组中输出来自30个不同数字的7个数字的所有可能组合?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我使用这样的循环生成了数组.

For example I've array generated with the loop like this.

var array=[];
for(var i=1; i<=30; i++)
  {
   array.push(i);

  }
 console.log(array);

我想从数组中输出所有可能的7个数字组的组合.例如,样本输出可能看起来像:[1,5,14,4,30,23,19].如果我想用组合公式来计算可能的组合.会是这样的:n!/r!(n-r)!

I want to output the combination of all the possible group of 7 numbers from the array. For example a sample output may look like : [1,5,14,4,30,23,19]. If I would to calculate the possible combination with the combination formula. It would be something like this: n!/r!(n-r)!

这将是一个巨大的数字.我在这里找到了置换解决方案,但是它的作用是根据数组的长度打印出所有可能的数字.但是我需要从总共30个整数中找出7个数字的可能组合.

And it is going to be a huge number. I've found a permutation solution here, but what it does is that it prints out all the possible numbers according to the length of array. But my need is to find out the possible combination of 7 numbers from total 30 integers.

我将如何使用javascript在逻辑上和实践上解决此问题.

How would I solve this problem logically and practically with javascript.

推荐答案

您猜这就是您要找的吗?

guess this is what you're after?

function cartesian_product(xs, ys) {
    var result = [];
    for(var i = 0; i < xs.length; i++) {
        for (var j = 0; j < ys.length; j++) {
            // transform [ [1, 2], 3 ] => [ 1, 2, 3 ] and append it to result []
            result.push([].concat.apply([], [ xs[i], ys[j] ]));
        }
    }
    return result;
}

function cartesian_power(xs, n) {
    var result = xs;
    for(var i = 1; i < n; i++) {
        result = cartesian_product(result, xs)
    }
    return result;
}

// in your case params are [ 1, 2... 30] and 7
console.log(cartesian_power([1, 2, 3, 4], 2));

输出为:

[ [ 1, 1 ],
  [ 1, 2 ],
  [ 1, 3 ],
  [ 1, 4 ],
  [ 2, 1 ],
  [ 2, 2 ],
  [ 2, 3 ],
  [ 2, 4 ],
  [ 3, 1 ],
  [ 3, 2 ],
  [ 3, 3 ],
  [ 3, 4 ],
  [ 4, 1 ],
  [ 4, 2 ],
  [ 4, 3 ],
  [ 4, 4 ] ]

更新

这将需要更少的内存,因为它不会存储任何内容,只会打印输出.但仍然怀疑它是否实用.

this one will require much less memory, since it will not store anything, it will just print the output. but still doubt it's practical.

function print_combs(arr, n, out) {
    if (n === 0) {
        console.log(out);
    } else {
        for(var i = 0; i < arr.length; i++) {
            print_combs(arr, n-1, out+arr[i]);
        }
    }
}

print_combs([1, 2, 3, 4], 2, "");

这篇关于如何在JavaScript数组中输出来自30个不同数字的7个数字的所有可能组合?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆