如何在JavaScript中获取多列表的唯一索引组合并追踪元素来源?
解决方案
给定四个长度均为5的列表,要求生成所有元素索引不重复的组合(即每个组合中,四个元素的索引互不相同),同时记录每个元素的来源列表,可通过以下步骤实现:
思路
核心是生成所有长度为4的不重复索引序列(索引范围0-4),每个序列对应从四个列表中依次选取对应索引的元素,同时记录元素的来源信息。
代码实现(JavaScript)
// 定义原始列表及来源标识 const list1 = [1,2,3,4,5] const list2 = [6,7,8,9,10] const list3 = [11,12,13,14,15] const list4 = [16,17,18,19,20] const lists = [ { name: 'list1', data: list1 }, { name: 'list2', data: list2 }, { name: 'list3', data: list3 }, { name: 'list4', data: list4 } ]; // 生成所有长度为k的不重复索引序列(索引范围0~n-1) function generateUniqueIndices(n, k) { const result = []; const backtrack = (current, used) => { if (current.length === k) { result.push([...current]); return; } for (let i = 0; i < n; i++) { if (!used.has(i)) { used.add(i); current.push(i); backtrack(current, used); current.pop(); used.delete(i); } } }; backtrack([], new Set()); return result; } // 生成所有符合要求的带来源信息的组合 const validCombinations = generateUniqueIndices(5, 4).map(indices => { return indices.map((idx, listIdx) => { const { name, data } = lists[listIdx]; return { value: data[idx], source: name, index: idx }; }); });
说明
- 索引生成逻辑:
generateUniqueIndices通过回溯法遍历所有可能的索引组合,确保每个序列中的索引互不重复,最终得到所有符合要求的索引序列(共5×4×3×2=120种)。 - 组合生成逻辑:遍历每个索引序列,从对应列表中取出元素,同时封装元素的值、来源列表名和使用的索引,得到带来源信息的有效组合。
示例有效组合
以下是几个符合要求的组合示例:
- 组合1:
[ { value: 1, source: 'list1', index: 0 }, { value: 7, source: 'list2', index: 1 }, { value: 13, source: 'list3', index: 2 }, { value: 19, source: 'list4', index: 3 } ] - 组合2:
[ { value: 2, source: 'list1', index: 1 }, { value: 6, source: 'list2', index: 0 }, { value: 14, source: 'list3', index: 3 }, { value: 20, source: 'list4', index: 4 } ]
内容的提问来源于stack exchange,提问作者Frinch87
相关产品推荐
相关产品推荐

