Advertisement
debetimi

meh.scala

Mar 25th, 2014
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 2.08 KB | None | 0 0
  1. package s99
  2.  
  3. /**
  4.  * Created by timi on 3/24/14.
  5.  */
  6. object NinetyNineScalaProblems {
  7.  
  8.   import java.util.NoSuchElementException
  9.  
  10.   def last[A](info: List[A]): A = {
  11.     info.last
  12.   }
  13.  
  14.   def penultimate[A](info: List[A]): A = {
  15.     if (info.size < 2) throw new NoSuchElementException()
  16.     else info.init.last
  17.   }
  18.  
  19.   def nth[A](n: Int, info: List[A]): A = {
  20.     if (n >= info.length || n < 0) throw new NoSuchElementException
  21.     else info(n)
  22.   }
  23.  
  24.   def length(ls: List) = {
  25.     ls.length
  26.   }
  27.  
  28.   def reverse[A](ls: List[A]) = ls.reverse
  29.  
  30.   def isPalindrome[A](ls: List[A]) = {
  31.     ls == ls.reverse
  32.   }
  33.  
  34.   def flatten(ls: List[Any]): List[Any] = {
  35.     ls.flatMap(
  36.     {
  37.       case x: List[_] => flatten(x)
  38.       case e => List(e)
  39.     }
  40.     )
  41.   }
  42.  
  43.   def compress[A](ls: List[A]) = {
  44.     ls.foldRight(List[A]())(
  45.       (a, b) => {
  46.         if (!b.isEmpty && b.head == a) b else a :: b
  47.       }
  48.     )
  49.   }
  50.  
  51.   def pack[A](ls: List[A]) = {
  52.     ls.foldRight(List[List[A]]())(
  53.       (cur, listOfLists) => {
  54.         if (listOfLists.isEmpty
  55.           || listOfLists.head.head != cur) {
  56.           List(cur) :: listOfLists
  57.         } else {
  58.           (cur :: listOfLists.head) :: listOfLists.tail
  59.         }
  60.       }
  61.     )
  62.   }
  63.  
  64.   def encode[A](ls: List[A]): List[(Int, A)] = {
  65.     pack(ls).map(
  66.       f => (f.length, f.head)
  67.     )
  68.   }
  69.  
  70.   def encodeModified[A](ls: List[A]) = {
  71.     pack(ls).map(
  72.       f => f match {
  73.         case e :: Nil => e
  74.         case _ => (f.length, f.head)
  75.       }
  76.     )
  77.   }
  78.  
  79.   def decode[A](ls: List[(Int, A)]) = {
  80.     def helper(n: Int, elem: List[A]): List[A] = {
  81.       if (n == 1) elem
  82.       else helper(n - 1, elem.head :: elem)
  83.     }
  84.     ls.flatMap((x) => helper(x._1, List(x._2)))
  85.   }
  86. 2
  87.   def duplicate[A](ls: List[A]) = {
  88.     ls.map(List.fill(2)(_)).flatten
  89.   }
  90.  
  91.   def split[A](n: Int, ls: List[A]) = {
  92.     ls splitAt n
  93.   }
  94.  
  95.   def slice[A](i: Int, j: Int, ls: List[A]) = {
  96.     ls.slice(i, j)
  97.   }
  98.  
  99.   def rotate[A](n: Int, ls: List[A]) = {
  100.     val (a, b) = ls.splitAt((n + ls.length) % ls.length)
  101.     b ::: a
  102.   }
  103. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement