例如,我用这样的循环生成数组。
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) !
这将是一个巨大的数字。我找到了一个排列解,但是它所做的是根据数组的长度打印出所有可能的数字。但是我需要从总共30个整数中找出7个数字的可能组合。
如何用javascript在逻辑上和实践上解决这个问题
你猜这就是你想要的吗?
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 ] ]
这个将需要更少的内存,因为它不会存储任何东西,它只会打印输出。但我仍然怀疑它的实用性。
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, "");
首先:这将生成bincoef(7,30)
个整数集,大约是200万个。集合,所以你应该认真考虑是否需要这么多的数据,因为这个算法会生成大量的数据,并且需要相当多的数据。我只能提供伪代码,因为我的javascript知识相当基础。
void nextPermutation(int[] in, int[] set, int last_from_input, int at_element)
//we can't generate further permutations from this position, since
//there is aren't enough elements in the input-array left
if(last_from_input >= 30 - at_element)
return
//the set is filled -> process the produced set
if(at_element === 7)
print(set)//process permutation
return
//add one element to the set and proceed with further elements
for(int i in ]last_from_input, length(in) - (7 - at_element)[
set[at_element] = in[i]
nextPermutation(in , set , i, at_element + 1)
基本上这个算法得到以下参数:
- in:要从 中选择的30整数
- set:包含到目前为止我们添加的所有元素的petmutation的当前部分
- last_from_input:我们添加到set 中的最后一个元素的索引
- at_element:当前正在搜索的集合中元素的索引
这个算法基本上是添加一个索引比上一个添加的元素高的元素,然后继续递归搜索下一个元素。如果设置完成,则可以进行处理。如果完成集合所需的元素比剩下的元素多,那么就不可能完成集合,我们可以中断这部分的搜索。这不是最佳实现关于效率,但我尽量保持事情简单
现在我们可以简单地以这种方式生成所有排列:
void genPermutations(int[] in)
nextPermutation(in , new int[7],-1,0)