javascript - 通过 JS 求 n 个列表的交集

标签 javascript list intersection

我正在研究一种算法,并试图根据以下信息找出如何解决它:

  1. 我想找到 n 个列表之间的交集
  2. 假设我有一个(正常工作的)intersection(a, b) 函数
  3. 假设交集()只接受两个列表作为输入

所以问题看起来像这样:

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/

相关文章:

javascript - Raphael.js 通过多个对象的交集创建透明度

Python:更改 np.array 的格式或允许 in1d 函数中的容差

javascript - 离开 IE 选项卡会发生什么事件?

c++ - 我如何定义 map::iterator 列表和 list::iterator 映射

javascript - 什么是仅返回 SSN 的数字部分的 javascript 正则表达式

python - 如何在Python中对具有浮点值的列表进行排序?

python - 如何在Python中使用OnClick事件保存列表以将它们添加到单个列表中并获得交集

c# - 线与 AABB 矩形相交?

javascript - JSON 结构和返回

javascript - 在 reducer 中状态更改后组件不会重新渲染