Scala从列表中生成唯一对

Co_*_*_42 12 functional-programming scala

输入:

val list = List(1, 2, 3, 4)
Run Code Online (Sandbox Code Playgroud)

期望的输出:

Iterator((1, 2), (1, 3), (1, 4), (2, 3), (2, 4), (3, 4))
Run Code Online (Sandbox Code Playgroud)

此代码有效:

for (cur1 <- 0 until list.size; cur2 <- (cur1 + 1) until list.size)
  yield (list(cur1), list(cur2))
Run Code Online (Sandbox Code Playgroud)

但它似乎不是最佳的,有没有更好的方法呢?

acj*_*jay 23

.combinations内置了一种方法:

scala> List(1,2,3,4).combinations(2).toList
res0: List[List[Int]] = List(List(1, 2), List(1, 3), List(1, 4), List(2, 3), List(2, 4), List(3, 4))
Run Code Online (Sandbox Code Playgroud)

它返回一个Iterator,但我添加的.toList只是为了打印结果.如果您希望以元组形式显示结果,则可以执行以下操作:

scala> List(1,2,3,4).combinations(2).map{ case Seq(x, y) => (x, y) }.toList
res1: List[(Int, Int)] = List((1,2), (1,3), (1,4), (2,3), (2,4), (3,4))
Run Code Online (Sandbox Code Playgroud)

您也提到了唯一性,因此您可以应用于.distinct您的输入列表,唯一性不是您的功能的先决条件,因为.combination不会为您进行重复数据删除.

  • @ Co_42:替代解决方案:`list.tails.collect {case h :: tail => tail map {(h,_)}} .flatten.toList`. (3认同)