scala通过遍历树更新hashmap

时间:2015-09-07 06:15:16

标签: scala

我是scala的新手,并试图找到最好的递归方式来解决我的问题。 我已经构建了一个n树,每个节点都对应一个带有和id的模式:

Null
-1:id1
--2:id2
--4:id3
---8:id4

存储以下模式:

(1)
(1,2)
(1,4)
(1,4,8)

我还有一组带有时间戳的项目集序列:

[3, (1,2,3)], [6, (1,4,5)]
...

我希望为每个序列获取模式id的hashmap以及相应的时间戳。

[[id1, [[3,3],[6,6]]],[id2, [3,3]],[id3, [6,6]]]

我发现了一个我认为非常难看的解决方案:

class ItemSet[T] (
  val items: Array[T],
  val timestamp: Long) extends Serializable{}

class PatternTree extends Serializable {
  import PatternTree._
  val root: PatternNode = new PatternNode(null)
  ...
object PatternTree {
  class PatternNode (val parent: PatternNode) extends Serializable {
    var patternId:[Int] = _
    var children:mutable.HashMap[Int, PatternNode] = mutable.HashMap.empty
    ...
  }
}

val tree = new PatternTree
tree.add(Array(1))
tree.add(Array(1,2))
tree.add(Array(1,4))
tree.add(Array(1,4,8))

val map: mutable.HashMap[Int, mutable.ArrayBuffer[Array[Long]]] = mutable.HashMap.empty
val sequence: Array[ItemSet[Int]] = Array(new ItemSet(Array(1, 2), 1), new ItemSet(Array(1, 3), 2))

sequence.foreach { x =>
  for (i <- 0 to x.items.size - 1) {
    traverse(x.timestamp, x.items.drop(i), tree.root, map)
  }
}

def traverse(timestamp: Long, items: Array[Int], node: PatternNode, IdList: mutable.HashMap[Int, mutable.ArrayBuffer[Array[Long]]]): Unit = {
  if (!items.isEmpty) {
    if (node.children.contains(items(0))) {
      val newNode = node.children.get(items(0)).get
      IdList.getOrElseUpdate(newNode.patternId, new mutable.ArrayBuffer[Array[Long]]) += (Array(timestamp, timestamp))
      if (items.size > 1) {
        traverse(timestamp, items.drop(1), node.children.get(items(0)).get, IdList)
      }
    }
  }
}

我有兴趣以更优雅的方式使用scala功能,折叠吗?

0 个答案:

没有答案