我正在研究一种算法,并试图根据以下信息找出如何解决它:
- 我想找到 n 个列表之间的交集
- 假设我有一个(正常工作的)intersection(a, b) 函数
- 假设交集()只接受两个列表作为输入
所以问题看起来像这样:
var a = {1, 2, 'b'};
var b = {2, 'b', 'b'};
var c = {2, 'b', 'c'};
var d = {'a', 'b', 'c'};
//this is the part that does not work, of course:
function intersect_all(d)
{
//what goes in here???
}
注意:我不想为此使用 python,因为 python 的 lang 内置方法不适用于我的应用程序(或 js)。我想用上面的信息来解决这个问题。
结果应该类似于
{2, 'b'}
jml
最佳答案
假设您有一个列表数组:
var lists = [];
lists[0] = [1, 2, 'b'];
lists[1] = [2, 'b', 'b'];
lists[2] = [2, 'b', 'c'];
lists[3] = ['a', 'b', 'c'];
然后你可以使用这个:
// say you call this passing the array of lists as the argument: intersect_all(lists)
function intersect_all(lists)
{
if (lists.length == 0) return [];
else if (lists.length == 1) return lists[0];
var partialInt = lists[0];
for (var i = 1; i < lists.length; i++)
{
partialInt = intersection(partialInt, lists[i]);
}
return partialInt;
}
关于javascript - 通过 JS 求 n 个列表的交集,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5837295/