Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
570 views
in Technique[技术] by (71.8m points)

javascript - intersection of n lists via JS

I am working on an algorithm and trying to figure out how to solve it given the following information:

  1. I would like to find the intersection between n number of lists
  2. assume that I have a (properly working) intersection(a, b) function
  3. assume that the intersection() only takes two lists as input

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???        
}

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.

The result should look something like

{2, 'b'}

jml

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

Let's say you have an array of lists instead:

var lists = [];
lists[0] = [1, 2, 'b']; 
lists[1] = [2, 'b', 'b'];
lists[2] = [2, 'b', 'c'];
lists[3] = ['a', 'b', 'c'];

Then you can use this:

// 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;
}

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...