[英]Create Possible Combination in javascript/typescript/nodejs
let input = [ 1, 2, 3, 4, 5, 6, 7, 8, 9, 10 ]
and i want output should be:我希望输出应该是:
output = {
first: [[1,2], [3,4], [5,6], [7,8], [9,10]],
second: [[1,3], [2,4], [5,7], [6,9], [8,10]],
third: [[1,4], [2,3], [5,8], [7,9], [6,10]],
fourth: [[1,5], [2,6], [3,7], [8,9], [4,10]],
fifth: [[1,6], [2,8], [3,5], [4,9], [7,10]],
sixth: [[1,7], [2,9], [3,6], [4,8], [5,10]],
seventh: [[1,8], [2,7], [4,6], [5,9], [3,10]],
eighth: [[1,9], [3,8], [4,5], [6,7], [2,10]],
ninth: [[1,10], [2,5], [3,9], [4,7], [6,8]],
}
I need to write a code in javascript / typescript / nodejs by which i can put number ranges and will get a combinations of given numbers**( n-1 ) , i want a code to be written which can return us **all possible combination and the combination will never conflict with other combinations .我需要在javascript/typescript/nodejs 中编写一个代码,通过它我可以放置数字范围并获得给定数字的组合**(n-1) ,我想要编写一个可以返回我们**所有可能的代码组合和组合永远不会与其他组合发生冲突。
Thanks in advance.提前致谢。
You could take a brute force approach with a recursive function for collected pairs and a list of available pairs.您可以对收集的对和可用对的列表采用递归函数的蛮力方法。
If a new pair is possible to get, take this pair and call the function again.如果可以得到一个新的对,取这个对并再次调用该函数。
function getAllPairs(array) { var pairs = []; for (let i = 0; i < array.length - 1; i++) { for (let j = i + 1; j < array.length; j++) { pairs.push([array[i], array[j]]); } } return pairs; } function fill(pairs, result = []) { function check(array) { return array.every((s => a => a.every(v => !s.has(v) && s.add(v)))(new Set)); } if (!pairs.length) return result; var left = result.slice(Math.floor(result.length / half) * half); for (let i = 0; i < pairs.length; i++) { if (!check([...left, pairs[i]])) continue; var newResult = fill([...pairs.slice(0, i), ...pairs.slice(i + 1)], [...result, pairs[i]]); if (newResult) return newResult; // i miss something like returnIf } } var data = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10], half = data.length / 2, temp = fill(getAllPairs(data)), result = [], i = 0; while (i < temp.length) result.push(temp.slice(i, i += half)); result.forEach(a => console.log(...a.map(a => a.map(v => v.toString().padStart(2, ' ')).join('|'))));
.as-console-wrapper { max-height: 100% !important; top: 0; }
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.