【问题标题】:Scala : Sorting list of number based on another listScala:基于另一个列表对数字列表进行排序
【发布时间】:2017-04-30 02:20:35
【问题描述】:

我正在 scala 中实现一种算法,其中我有一组节点(整数),并且每个节点都有一个与之关联的属性,让我们将该属性称为“d”(它又是一个整数)。

我有一个 list[Int] ,这个列表包含按值“d”降序排列的节点。

我还有一个 Map[Int,Iterable[Int]] ,这里的键是一个节点,值是它所有邻居的列表。

问题是,如何按属性 "d" 的降序存储 Map 中节点的邻居列表。

示例:

List 1 : List[1,5,7,2,4,8,6,3] --> 想象一下这个列表按某种顺序排序并包含所有数字。

Map : [Int,Iterable][Int]] --> [1 , Iterable[2,3,4,5,6]]

此可迭代对象可能包含所有数字,也可能不包含所有数字。

简单来说,我希望 Iterable 中的数字与列表 1 中的数字顺序相同。

所以我在 Map 中的输入应该是:[1, Iterable[5,2,4,6,3]]

【问题讨论】:

  • 我很难理解你的问题。请添加一些未实现或伪代码,并附上示例来演示您要查找的内容。
  • 我已经更新了这个问题,希望对您有所帮助。
  • map.mapValues(neighbors => list.filter(neighbors.contains)) 怎么样?

标签: algorithm scala sorting data-structures


【解决方案1】:

最简单的方法是过滤排序列表。

val list = List(1,5,7,2,4,8,6,3)
val map = Map(1 -> List(2,3,4,5,6),
              2 -> List(1,2,7,8))
val map2 = map.mapValues(neighbors => list.filter(neighbors.contains))
println(map2)

【讨论】:

  • 这个解决方案很适合我的算法。也非常省时。非常感谢。
【解决方案2】:

这是使用foldLeft 的可能解决方案(请注意,我们在末尾得到ArrayBuffer,而不是所需的Iterable,但类型签名确实显示Iterable):

scala> val orderTemplate = List(1,5,7,2,4,8,6,3)
orderTemplate: List[Int] = List(1, 5, 7, 2, 4, 8, 6, 3)

scala> val toOrder = Map(1 -> Iterable(2,3,4,5,6))
toOrder: scala.collection.immutable.Map[Int,Iterable[Int]] = Map(1 -> List(2, 3, 4, 5, 6))

scala> val ordered = toOrder.mapValues(iterable =>
  orderTemplate.foldLeft(Iterable.empty[Int])((a, i) =>
    if (iterable.toBuffer.contains(i)) a.toBuffer :+ i
    else a
  )
)
ordered: scala.collection.immutable.Map[Int,Iterable[Int]] = Map(1 -> ArrayBuffer(5, 2, 4, 6, 3))

【讨论】:

  • 非常感谢。这个解决方案也很好用:)
【解决方案3】:

这就是我得到的。

val lst = List(1,5,7,2,4,8,6,3)
val itr = Iterable(2,3,4,5,6)

itr.map(x => (lst.indexOf(x), x))
   .toArray
   .sorted
   .map(_._2)
   .toIterable       // res0: Iterable[Int] = WrappedArray(5, 2, 4, 6, 3)
  1. 我将每个条目与其在完整列表中的相对索引结合起来。
  2. 无法对可迭代对象进行排序,所以使用Array(无特殊原因)。
  3. 元组排序默认为第一个元素。
  4. 删除索引。
  5. 返回Iterable

【讨论】:

  • 谢谢。效果很棒:)
猜你喜欢
  • 1970-01-01
  • 2012-06-01
  • 2022-07-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-03-29
  • 2012-02-08
  • 1970-01-01
相关资源
最近更新 更多