题目描述:
Decode a run-length encoded list.
Given a run-length code list generated as specified in problem P10, construct its uncompressed version.
Example: scala> decode(List((, 'a), (1, 'b), (, 'c), (2, 'a), (, 'd), (4, 'e)))
res0: List[Symbol] = List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)
根据List中的元素,将其展开, 与之前的encodeList 做相反的操作。
思路: 使用之前提到的foldLeft函数, 从左到右遍历List,将其每一个元组展开,放入初始值里面。
代码:
def decodeList[T](a:List[(Int, T)]): List[T] = a.foldLeft(List[T]()){
case (res, cur) => {
val count = cur._1
val content = cur._2
res:::List.fill(count)(content)
}
}
val b = List((, "a"), (,"zb"))
println(decodeList(b))
List.fill:
def fill[A](n: Int)(elem: => A): CC[A] = {
val b = newBuilder[A]
b.sizeHint(n)
var i =
while (i < n) {
b += elem
i +=
}
b.result
}
向集合中插入n个类型为A的元素。