勉強のためにListのAPIはなるべく使わない方向で。
// P10 (*) Run-length encoding of a list. // Use the result of problem P09 to implement the so-called run-length encoding data compression method. Consecutive duplicates of elements are encoded as tuples (N, E) where N is the number of duplicates of the element E. // Example: // scala> encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e)) // res0: List[(Int, Symbol)] = List((4,'a), (1,'b), (2,'c), (2,'a), (1,'d), (4,'e)) def pack[A](ls: List[A]): List[List[A]] = { if (ls.isEmpty) List(List()) else { val (packed, next) = ls span { _ == ls.head } if (next == Nil) List(packed) else{ packed :: pack(next) } } } def encode[T](xs: List[T]) = { pack(xs).map{ (x) => (x.length, x.head) } } def encodeModified[T](xs: List[T]) = { pack(xs).map{ (x) => if(x.length == 1) x.head else (x.length, x.head) } }
解答例
同じだ。
No comments:
Post a Comment