[英]All possible array combinations algorithm (hungarian, bruteforce)
Got task to resolve (person tracking on computer vision) and i have somehow to get all possible combinations of 2 arrays. 得到解决的任务(对计算机视觉的人员跟踪),我以某种方式获得了2个阵列的所有可能组合。 Input: two arrays 输入:两个数组
arr1 = ['a', 'b', 'c'];
arr2 = [1, 2, 3];
Task is to write (probably recursive) algo to output array of all possible combinations like this: 任务是将算法(可能是递归的)写到所有可能组合的输出数组,如下所示:
[
{a:1, b:2, c:3},
{a:1, b:3, c:2},
{a:2, b:1, c:3},
{a:2, b:3, c:1},
{a:3, b:1, c:2},
{a:3, b:2, c:1},
]
Input arrays may not be same length. 输入数组的长度可能不相同。 For example 例如
arr1 = [a,b];
arr2 = [1,2,3];
// =>
[
{a:1, b:2},
{a:1, b:3},
{a:2, b:1},
{a:2, b:3},
{a:3, b:1},
{a:3, b:2}
]
Or like this 或者像这样
arr1 = [a,b,c];
arr2 = [1,2];
// =>
[
{a:1, b:2},
{a:1, c:2},
{b:1, a:2},
{b:1, c:2},
{c:1, a:2},
{c:1, b:2}
]
Perfectly would be structure like this 完全是这样的结构
[
{
combo: {a:1, b:2, c:3}
},
...
]
...but it doesn't really matter ...但这并不重要
There are lots of topics here on stackoverflow like this, but all those algos are a bit different and easier. 像这样的stackoverflow上有很多主题,但是所有这些算法都有些不同并且更容易。 They all give something like this: 他们都给出这样的东西:
[a1, a2, b1, b2, c1, c2]
I've gotten this so far: 到目前为止,我已经做到了:
const combos = (arr1, arr2, func) => {
let result = [];
for(let item1 of arr1){
let subcombo = {};
let subArr1 = Object.assign({}, arr1);
delete subArr1[item1];
for(let item2 of arr2){
subcombo[item] = {};
}
}
};
function give1() {
return 1;
}
let arr1 = ['a', 'b', 'c'];
let arr2 = ['x', 'y', 'z'];
const res = combos(arr1, arr2, give1);
console.log(res);
You can first create function to do permutations with limit and then based on the length of keys and values do the permutation of keys if keys.length > values.length
otherwise do permutation of values and after that create array of objects from that result. 您可以首先创建函数以进行限制置换,然后如果keys.length > values.length
则根据键和值的长度对键进行置换,否则对值进行置换,然后根据该结果创建对象数组。
function permute(data, len) { let result = [] function generate(data, n, c) { if(!data.length) { result.push(c.slice(0, len)); return; } for(var i = 0; i < data.length; i++) { c[n] = data[i] let copy = [...data] copy.splice(i, 1); generate(copy, n + 1, c) } } generate(data, 0, []) return result; } function f(keys, vals) { let byKeys = keys.length > vals.length, permuted = null if(byKeys) permuted = permute(keys, vals.length); else permuted = permute(vals, keys.length); return permuted.map(arr => arr.reduce((r, e, i) => { byKeys ? r[e] = vals[i] : r[keys[i]] = e return r; }, {})) } console.log(f(['a', 'b', 'c'], [1, 2, 3])) console.log(f(['a', 'b', 'c'], [1, 2])) console.log(f(['a', 'b'], [1, 2, 3]))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.