Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

extract common elements from lists in dart

Tags:

flutter

dart

i have 3 Lists, for example:

  List l1 = [1, 2, 3, 55, 7, 99, 21];
  List l2 = [1, 4, 7, 65, 99, 20, 21];
  List l3 = [0, 2, 6, 7, 21, 99, 26];

and i expect the common elements:

// [7,99,21]

here is what i've tried but didn't work correctly:

 List l1 = [1, 2, 3, 55, 7, 99, 21];
 List l2 = [1, 4, 7, 65, 99, 20, 21];
 List l3 = [0, 2, 6, 7, 21, 99, 26];
 List common = l1;

 l2.forEach((element) {
   l3.forEach((element2) {
    if (!common.contains(element) || !common.contains(element2)) {
    common.remove(element);
    common.remove(element2);
    }
   });
 });

print(common);

plus, the number of lists is dynamic, so i expect to nest them like this, i have no experience with recursion so i couldn't do it or even know if it's better than nesting loops.

thanks for helping.

like image 578
Waleed Alenazi Avatar asked Dec 20 '19 22:12

Waleed Alenazi


2 Answers

You don't need nested loops or recursion for this. Dart has Sets and a very nice fold method on Lists.

main() {
  final lists = [
    [1, 2, 3, 55, 7, 99, 21],
    [1, 4, 7, 65, 99, 20, 21],
    [0, 2, 6, 7, 21, 99, 26]
  ];

  final commonElements =
      lists.fold<Set>(
        lists.first.toSet(), 
        (a, b) => a.intersection(b.toSet()));

  print(commonElements);
}

Gives:

{7, 99, 21}

Further, this can be used no matter how many lists are contained in lists.

like image 197
Richard Ambler Avatar answered Sep 28 '22 01:09

Richard Ambler


One solution :

void main() {
  List l1 = [1, 2, 3, 55, 7, 99, 21];
  List l2 = [1, 4, 7, 65, 99, 20, 21];
  List l3 = [0, 2, 6, 7, 21, 99, 26];

  l1.removeWhere((item) => !l2.contains(item));
  l1.removeWhere((item) => !l3.contains(item));

  print(l1);
}

Result :

[7, 99, 21]

If your number of lists is dynamic, then a solution is to count all occurences within all the lists, and retains only values where number of occurence is equals to the number of lists :

void main() {
  List<List> lists = [
    [1, 2, 3, 55, 7, 99, 21],
    [1, 4, 7, 65, 99, 20, 21],
    [0, 2, 6, 7, 21, 99, 26]
  ];

  Map map = Map();
  for (List l in lists) {
    l.forEach((item) => map[item] = map.containsKey(item) ? (map[item] + 1) : 1);
  }

  var commonValues = map.keys.where((key) => map[key] == lists.length);

  print(commonValues);
}

Result :

(7, 99, 21)

like image 44
Yann39 Avatar answered Sep 28 '22 00:09

Yann39