Advertisement
Guest User

Untitled

a guest
Jun 11th, 2014
178
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.33 KB | None | 0 0
  1. def toRoman(num: Int): String = {
  2.   def convertDigit(ten: String, five: String, one: String) = (num:Int) => (num%10) match {
  3.     case 9 => one + ten
  4.     case d if d>=5 => five + one*(d-5)
  5.     case 4 => one + five
  6.     case d => one*d
  7.   }
  8.  
  9.   val units = convertDigit("X","V","I")
  10.   val tens = convertDigit("C","L","X")
  11.   val hundreds = convertDigit("M","D","C")
  12.   val thousands = convertDigit("","","M")
  13.  
  14.   thousands(num/1000) + hundreds(num/100) + tens(num/10) + units(num)
  15. }
  16.  
  17. def iterate[A,B](f: (A, B) => A, initial_value: A, L: List[B]): A = {
  18.   def iter(a: A, L: List[B]) : A = L match {
  19.     case Nil => a
  20.     case x::xs => iter(f(a, x), xs)
  21.   }
  22.  
  23.   iter(initial_value, L)
  24. }
  25.  
  26. def sum(L: List[Int]) = iterate((x: Int, y: Int) => x + y, 0, L)
  27. def sum(L: List[Int]) = iterate((_: Int) + (_: Int), 0, L)
  28.  
  29. def splitAt[A](L: List[A], n: Int): (List[A], List[A]) = (L, n) match {
  30.   case (L, 0) => (Nil, L)
  31.   case (Nil, _) => (Nil, Nil)
  32.   case (x::xs, n) => splitAt(xs, n - 1) match {
  33.     case (left, right) => (x::left, right)
  34.   }
  35.  
  36. }
  37.  
  38. def countChange(amount: Int, coins: List[Int]): Int = (amount, coins) match {
  39.   case (0, _) => 1
  40.   case (_, Nil) => 0
  41.   case (amount, x::xs) => {
  42.     val withx = if (amount >= x) countChange(amount - x, coins) else 0
  43.     val withoutx = countChange(amount, xs)
  44.  
  45.     withx + withoutx
  46.   }
  47. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement