我有这个随机组合生成器,它按照我想要的数字找到给定数组的每个可能组合:
var Util = function() {
};
Util.getCombinations = function(array, size, start, initialStuff, output) {
if (initialStuff.length >= size) {
output.push(initialStuff);
} else {
var i;
for (i = start; i < array.length; ++i) {
Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
}
}
}
Util.getAllPossibleCombinations = function(array, size, output) {
Util.getCombinations(array, size, 0, [], output);
}
var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
for (var i=1; i<=array; ++i) {
array[i - 1] = i;
}
var output = [];
Util.getAllPossibleCombinations(array, 2, output);
console.log(output);
document.write(output);
JSfiddle:http://jsfiddle.net/n1sqbrw2/
我希望输出看起来像这样:
document.write(var + ', ');
ab, ac, ad, ae, af, ...
我需要在此脚本中编辑以美化输出?
感谢您的帮助!
答案 0 :(得分:1)
使用 map()
将output
中的每个数组更改为字符串,然后使用 join(', ')
来美化:
output.map(function(val) {
return val.join(''); //join the array to make a string
}).join(', '); //join the strings to beautify
var Util = function() {};
Util.getCombinations = function(array, size, start, initialStuff, output) {
if (initialStuff.length >= size) {
output.push(initialStuff);
} else {
var i;
for (i = start; i < array.length; ++i) {
Util.getCombinations(array, size, i + 1, initialStuff.concat(array[i]), output);
}
}
}
Util.getAllPossibleCombinations = function(array, size, output) {
Util.getCombinations(array, size, 0, [], output);
}
var array = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x', 'y', 'z', '0', '1', '2', '3', '4', '5', '6', '7', '8', '9'];
for (var i = 1; i <= array; ++i) {
array[i - 1] = i;
}
var output = [];
Util.getAllPossibleCombinations(array, 2, output);
console.log(output.map(function(val) {
return val.join('');
}).join(', '));