通过JS的n个列表的交集 [英] intersection of n lists via JS
本文介绍了通过JS的n个列表的交集的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我正在研究一种算法并试图找出如何解决它,并给出以下信息:
I am working on an algorithm and trying to figure out how to solve it given the following information:
- 我想找到n个列表之间的交集
- 假设我有一个(正常工作)交叉点(a,b)函数
- 假设交点( )只需要两个列表作为输入
所以问题看起来像这样:
So the problem would look something like this:
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,就此而言)。我想用上面的信息解决它。
Note: I don't want to use python for this, since python has methods built into the lang that are not available for my app (or js, for that matter). I would like to solve it using the above information.
结果应该类似于
{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;
}
这篇关于通过JS的n个列表的交集的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文