Solved: How can I reach unique pairs in nested list in Dart?

Question

Asked by Tugrul G on December 09, 2021 (source).

I have code example like this :

enter image description here

Here I want to access only unique pairs within the intArr list. I wanted to output like this ; [0, 0] [1, 1] [1, 2] [1, 3] For now, it doesn't matter if the pairs are in order from smallest to largest

Answer

Question answered by whygee (source).

You would store the lists that you have already printed in a variable List<List<int>> alreadySeen and check before printing if that variable contains the list to be printed.

void main() {
  List<List<int>> intArr = [
     [0, 0],
     [1, 1],
     [1, 1],
     [1, 2],
     [1, 3],
     [1, 2],
  ];
 
  List<List<int>> alreadySeen = [];
  
  for (int i = 0; i < intArr.length; i++) {
    if(!contains(alreadySeen, intArr[i])) {
      print(intArr[i]);
      alreadySeen.add(intArr[i]);
    }
  }
}

The function contains would have 2 nested for loops, one to loop through the main list and the other to loop through the list we are searching for. If the needle values match a list in the main list, the variable found stays true and the function returns true

bool contains(List<List<int>> list, List<int> needle) {
  if (list.length == 0 || needle.length == 0) return false;
  
  for (int i = 0; i < list.length; i++) {
    if (list[i].length != needle.length) continue;
    
    bool found = true;
    
    for(int j = 0; j < list[i].length; j++) {
      if (list[i][j] != needle[j]) found = false;
    } 
    
    if (found) return true;
  }
  
  return false;
}

Note that if you are using flutter there is a function named listEquals that would make the function contains easier see this however you can't use the basefunction intArr.contains since it will compare the reference of the arrays and not their values

Working Jdoodle.

As @jamesdlin pointed out, if performance is important to you, you would use a LinkedHashSet instead of List<List> for alreadySeen to make the contains function O(1) instead of O(n).

DART FLUTTER
SHARE: