将列表转换为在一个范围内只有一个项目

Transform list to have have only one item within a range

val test = List[Int](50, 115, 200, 50, 30, 22, 175, 350, 5000)

如果我有一个这样的列表,我想减少它,以便将彼此相差 50 以内的任何值都视为重复值,但我想保留其中一个值。

我现在有这个,但它删除了彼此之间 50 以内的所有那些,我希望每次都保留最高的一个。

test.filter(x => !test.exists(v => if(v == x) false else Math.abs(v - x) < 50));
List(115, 350, 5000)

因此理想情况下,此列表还包括 50 和 200。

编辑: 我实际上最终想为地图做这个。

val tmap = Map[String, String]("57" -> "550", "145" -> "2000", "85" -> "78", "40" -> "8556")

我想查看 50 以内的所有键,然后每次都在该范围内时获取数值最高的键。任何不在我保留范围内的。我希望这里的结果是。

Map(145 -> 2000, 40 -> 8556)

也许我应该提出一个新问题?

这就是你想要的吗?

val res = test.sorted.foldRight(List[Int]()) {
  (z, l) =>
    if (l.isEmpty) List(z)
    else if (l.head - z > 50) z +: l
    else l
}

输出:List(50, 115, 200, 350, 5000)

myMap
  .toSeq
  .sortWith(_._1.toLong < _._1.toLong)
  .foldLeft(Seq[(String, String)])((x, y) => {
    if(x.isEmpty) y +: x
    else if(Math.abs(x.last._1.toLong - y._1.toLong) < 50) {
      if(x.last._2.toLong < y._2.toLong) y +: x.dropRight(1)
      else x
    }
    else y +: x
  })

我认为这符合我对问题第二部分的要求。灵感来自 Toms 上面的答案。