Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- package s99
- /**
- * Created by timi on 3/24/14.
- */
- object NinetyNineScalaProblems {
- import java.util.NoSuchElementException
- def last[A](info: List[A]): A = {
- info.last
- }
- def penultimate[A](info: List[A]): A = {
- if (info.size < 2) throw new NoSuchElementException()
- else info.init.last
- }
- def nth[A](n: Int, info: List[A]): A = {
- if (n >= info.length || n < 0) throw new NoSuchElementException
- else info(n)
- }
- def length(ls: List) = {
- ls.length
- }
- def reverse[A](ls: List[A]) = ls.reverse
- def isPalindrome[A](ls: List[A]) = {
- ls == ls.reverse
- }
- def flatten(ls: List[Any]): List[Any] = {
- ls.flatMap(
- {
- case x: List[_] => flatten(x)
- case e => List(e)
- }
- )
- }
- def compress[A](ls: List[A]) = {
- ls.foldRight(List[A]())(
- (a, b) => {
- if (!b.isEmpty && b.head == a) b else a :: b
- }
- )
- }
- def pack[A](ls: List[A]) = {
- ls.foldRight(List[List[A]]())(
- (cur, listOfLists) => {
- if (listOfLists.isEmpty
- || listOfLists.head.head != cur) {
- List(cur) :: listOfLists
- } else {
- (cur :: listOfLists.head) :: listOfLists.tail
- }
- }
- )
- }
- def encode[A](ls: List[A]): List[(Int, A)] = {
- pack(ls).map(
- f => (f.length, f.head)
- )
- }
- def encodeModified[A](ls: List[A]) = {
- pack(ls).map(
- f => f match {
- case e :: Nil => e
- case _ => (f.length, f.head)
- }
- )
- }
- def decode[A](ls: List[(Int, A)]) = {
- def helper(n: Int, elem: List[A]): List[A] = {
- if (n == 1) elem
- else helper(n - 1, elem.head :: elem)
- }
- ls.flatMap((x) => helper(x._1, List(x._2)))
- }
- 2
- def duplicate[A](ls: List[A]) = {
- ls.map(List.fill(2)(_)).flatten
- }
- def split[A](n: Int, ls: List[A]) = {
- ls splitAt n
- }
- def slice[A](i: Int, j: Int, ls: List[A]) = {
- ls.slice(i, j)
- }
- def rotate[A](n: Int, ls: List[A]) = {
- val (a, b) = ls.splitAt((n + ls.length) % ls.length)
- b ::: a
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement