Monday, November 1, 2010

S10, S11

S-99: Ninety-Nine Scala Problemsを試してみる。
勉強のためにListのAPIはなるべく使わない方向で。

  1. // P10 (*) Run-length encoding of a list.  
  2. // 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.  
  3. // Example:  
  4. // scala> encode(List('a, 'a, 'a, 'a, 'b, 'c, 'c, 'a, 'a, 'd, 'e, 'e, 'e, 'e))  
  5. // res0: List[(Int, Symbol)] = List((4,'a), (1,'b), (2,'c), (2,'a), (1,'d), (4,'e))  
  6.   
  7. def pack[A](ls: List[A]): List[List[A]] = {  
  8.   if (ls.isEmpty) List(List())  
  9.   else {  
  10.     val (packed, next) = ls span { _ == ls.head }  
  11.     if (next == Nil) List(packed)  
  12.     else{  
  13.       packed :: pack(next)  
  14.     }  
  15.   }  
  16. }  
  17. def encode[T](xs: List[T]) = {  
  18.   pack(xs).map{ (x) => (x.length, x.head) }  
  19. }  
  20.   
  21. def encodeModified[T](xs: List[T]) = {  
  22.   pack(xs).map{ (x) => if(x.length == 1) x.head else (x.length, x.head) }  
  23. }  

解答例
同じだ。

No comments:

Post a Comment