如何筛选按非降序排列的元素列表

vsikbqxv  于 2021-07-14  发布在  Java
关注(0)|答案(2)|浏览(342)

如何筛选其他列表的列表,例如。

  1. val l = List(List(1,2,3), List(1,2,4), List(9,8,7))

返回不按降序排列的元素列表,列表中元素的总和为奇数。所以它应该会回来 List(1,2,4) (总和为7,元素不按降序排列)。
我在想 l.filter( _ < _ ).filter( _ + _ % 2 != 0) 但我真的不知道怎么做。

dpiehjr4

dpiehjr41#

您可以检查排序后的列表是否与列表本身相同:

  1. val filtered = l.filter(x => x.sorted == x && x.sum % 2 != 0)
tp5buhyn

tp5buhyn2#

尾部递归方法@luis指出:

  1. def isAscendingAndOddSum(xss: List[List[Int]]): List[List[Int]] = {
  2. @scala.annotation.tailrec
  3. def isAscendingAndOddSumR(xss: List[List[Int]], acc: List[List[Int]]): List[List[Int]] = xss match {
  4. case Nil => acc
  5. case h::t if(h.sorted == h && h.sum % 2 != 0) => isAscendingAndOddSumR(t, h :: acc)
  6. case h::t => isAscendingAndOddSumR(t, acc)
  7. }
  8. isAscendingAndOddSumR(xss, List())
  9. }
  10. scala> isAscendingAndOddSum(List(List(1,2,3), List(1,2,4), List(9,8,7)))
  11. val res11: List[List[Int]] = List(List(1, 2, 4))

相关问题