Scala过滤元组(x,y)==(y,x) [英] Scala filter tuples (x, y) == (y, x)

查看:176
本文介绍了Scala过滤元组(x,y)==(y,x)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如:

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

有一些元组,其中(x,y) ==(y,x),例如(5,0)和(0,5)。我只想留下其中的一个,例如第一个。

解决方案

使用foldLeft

 
ts.foldLeft(List [(Int,Int)]())
{(acc,el)=> if((acc contains el)||(acc contains el.swap))acc else else :: acc}
// List [(Int,Int)] = List((3,4),(2, 5),(0,5),(0,2))

O(n)版本(假设设置查找和添加是O(1))

$ t $ f $ p $ Int)]()){(acc,el)=>如果(acc(el.swap))acc其他acc + el}

如果我们重新排列那些交换元组不存在的地方(我猜这不是因为你没有指定哪个交换元组应该被保留):

  ts.map {t => if(t._1  // List [(Int,Int)] = List((0,2),(0,5),(2 ,5),(3,4))


I have a list of tuples, for example:

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

There are some tuples where (x, y) == (y, x), for example (5, 0) and (0, 5). I want to leave just one of them, for example first one. How can I do 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, with Sets for an O(n) version (assuming Set lookup and additions are O(1))

ts.foldLeft(Set[(Int,Int)]()){(acc, el) => if (acc(el.swap)) acc else acc + el}

If it doesn't matter if we re-order ones where the swapped tuple is not present (I'm guessing it doesn't as you don't specify which of the ones that have a swapped tuple should be 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))

这篇关于Scala过滤元组(x,y)==(y,x)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆