Re: Arrays Intersection



Infinity77 wrote:

I have received so many nice answers in this newsgroup that I
thought I could ask one more question. I am trying to find the
intersection of 2 one-dimensional integer arrays, where "intersection"
means the common elements in both arrays, i.e.:

a = [1,2,3,4,5,6]
b = [5, 6, 7]

intersection(a, b) ==> [5, 6]

Did someone else ask this recently? It sounds familiar.

Sort the two lists, if they aren't already.

You need an output array at least as long as the
shortest list. (Or it can be done in place, destroying
the input data.)

Initialize two index variables, one to the beginning
of each list, and start a loop. If the two elements
are equal, add to the output list and increment both
index variables. Otherwise increment the index variable
of the lower list element. Repeat until one is past the
end of its list.

-- glen

.



Relevant Pages

  • Re: RAD vs. performance
    ... arrays and lists are iterable containers which, while correct, applies to ... the optimisation phase. ... trade-off in the situations where this abstraction is useful but I think ...
    (comp.lang.misc)
  • Re: Compiler and an interpreter
    ... > Arrays are not more efficient than lists. ... > You should study the STL... ... For really complicate formulae, OCaml will be ...
    (comp.programming)
  • FAQ 4.39 What is the difference between a list and an array?
    ... This message is one of several periodic postings to comp.lang.perl.misc ... from the documentation provided with Perl. ... Subroutines are passed and return lists, ... context, you initialize arrays with lists, and you foreachacross a ...
    (comp.lang.perl.misc)
  • FAQ 4.39 What is the difference between a list and an array?
    ... This message is one of several periodic postings to comp.lang.perl.misc ... from the documentation provided with Perl. ... Subroutines are passed and return lists, ... context, you initialize arrays with lists, and you foreachacross a ...
    (comp.lang.perl.misc)
  • FAQ 4.39 What is the difference between a list and an array?
    ... This message is one of several periodic postings to comp.lang.perl.misc ... from the documentation provided with Perl. ... Subroutines are passed and return lists, ... context, you initialize arrays with lists, and you foreachacross a ...
    (comp.lang.perl.misc)