通过JS的n个列表的交集

编程入门 行业动态 更新时间:2024-10-25 17:25:41
本文介绍了通过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个列表的交集

    本文发布于:2023-11-29 18:30:32,感谢您对本站的认可!
    本文链接:https://www.elefans.com/category/jswz/34/1647243.html
    版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
    本文标签:列表   JS

    发布评论

    评论列表 (有 0 条评论)
    草根站长

    >www.elefans.com

    编程频道|电子爱好者 - 技术资讯及电子产品介绍!