Scala filter tuples (x, y) == (y, x) -


i have list of tuples, example:

  (0,2)   (0,5)   (2,0)   (2,5)   (3,4)   (4,3)   (5,0)   (5,2) 

there tuples (x, y) == (y, x), example (5, 0) , (0, 5). want leave 1 of them, example first one. how can it?

using foldleft

var ts = list((0,2),  (0,5),  (2,0), (2,5),  (3,4), (4,3), (5,0), (5,2))    ts.foldleft(list[(int,int)]())    {(acc, el) => if ((acc contains el) || (acc contains el.swap)) acc else el::acc} // list[(int, int)] = list((3,4), (2,5), (0,5), (0,2)) 

or, sets o(n) version (assuming set lookup , additions o(1))

ts.foldleft(set[(int,int)]()){(acc, el) => if (acc(el.swap)) acc else acc + el} 

if doesn't matter if re-order ones swapped tuple not present (i'm guessing doesn't don't specify of ones have swapped tuple should kept):

ts.map{t => if (t._1 < t._2) t else t.swap}.distinct // list[(int, int)] = list((0,2), (0,5), (2,5), (3,4)) 

Comments

Popular posts from this blog

c++ - QTextObjectInterface with Qml TextEdit (QQuickTextEdit) -

javascript - angular ng-required radio button not toggling required off in firefox 33, OK in chrome -

xcode - Swift Playground - Files are not readable -