繁体   English   中英

查找嵌套数组的所有可能组合

[英]Find all possible combinations of nested arrays

假设我有一个数字数组和一个数组,我想将其展平:

[1, [2, [3]] -> [1, 2, 3]

这很容易。 现在,让我们说,我想找到所有可能的组合,以便在任何时候,

[a, [b, c]] -> [[a, b], [a, c]]

我正在努力在这种结构中支持不可预测的和可能的高阶复杂性:

[1, [2, [3, 4]], [3, [4, [5, 6]], [7]] -> [[1, 2, 3], [1, 2, 4], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 7]

因此,这绝对是可映射/可归约的问题,但我无法解决这个问题。

您可以使用迭代和递归的方法并收集所有部分,并且仅当在实际的迭代数组中未找到任何数组时才进行推送。

 function combine(array) { var result = []; array.forEach(function iter(r, p) { return function (a, _, aa) { if (Array.isArray(a)) { a.forEach(iter(r, p + 1)); return; } r = r.slice(0, p); r[p] = a; aa.some(Array.isArray) || result.push(r); }; }([], 0)); return result; } console.log(combine([1, [2, [3]]])); // [[1, 2, 3]] console.log(combine(['a', ['b', 'c']])); // [["a", "b"], ["a", "c"]] console.log(combine([1, [2, [3, 4]], [3, [4, [5, 6]], [7]]])); // [[1, 2, 3], [1, 2, 4], [1, 3, 4, 5], [1, 3, 4, 6], [1, 3, 7]] 
 .as-console-wrapper { max-height: 100% !important; top: 0; } 

这不是一个完美定义的问题,但是从给定的数据中,我可以得出以下答案,该答案对于提供的输入集而言效果很好,并且对于该问题后面的隐含组合逻辑应该可以。

 var arr = [1, [2, [3, 4]]], brr = [1, [2, [3, 4]], [3, [4, [5, 6]], [7]]], flatNest = (a,p = []) => a.reduce((r,e,i,b) => Array.isArray(e) ? Array.isArray(b[i-1]) ? r.concat(flatNest(e,p)) : r : Array.isArray(b[i+1]) ? (r.push(...flatNest(b[i+1],[e]).map(f => p.concat(f))), p.push(e), r) : (r.push(p.concat(e)), r), []); console.log(JSON.stringify(flatNest(arr))); console.log(JSON.stringify(flatNest(brr))); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM