Programming-Idioms

This language bar is your friend. Select your favorite languages!

Idiom #218 List intersection

Create list c containing all unique elements that are contained in both lists a and b.
c should not contain any duplicates, even if a and b do.
The order of c doesn't matter.

using System.Linq;
using System.Collections.Generic;
c = a.Intersect(b).ToList();
seta := make(map[T]bool, len(a))
for _, x := range a {
	seta[x] = true
}
setb := make(map[T]bool, len(a))
for _, y := range b {
	setb[y] = true
}

var c []T
for x := range seta {
	if setb[x] {
		c = append(c, x)
	}
}
Classes
for elem in a do
  if (b.indexof(elem) >= 0) and (c.indexof(elem) = -1) then
    c.add(elem);
c = list(set(a) & set(b))
c = a & b

Do you know the best way to do this in your language ?
New implementation...

Idiom created by

programming-idioms.org

Related idioms