Advertisement
mitrakov

Count of sign changes

Apr 11th, 2019
418
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
Scala 1.42 KB | None | 0 0
  1. // Task: given a list of Integers. Find a count of intervals with the same sign.
  2. // Example: f(List(4, 5, -4, -5, 4, 5)) shouldBe 3
  3.  
  4. // imperative style
  5. object ChangeSign extends App {
  6.   def signChangeCount(list: List[Int]): Int = {
  7.     var sum = 0
  8.     if (list.nonEmpty) {
  9.       var current = -list.head    // we put "-" sign to count the first interval
  10.       for (i <- list) {
  11.         if (i * current < 0) {
  12.           sum += 1
  13.           current = i
  14.         }
  15.       }
  16.     }
  17.     sum
  18.   }
  19.  
  20.   println(signChangeCount(List.empty))                                    // 0
  21.   println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9)))                   // 3
  22.   println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9, -2, 5, -6, 0, 5)))  // 7
  23. }
  24.  
  25.  
  26.  
  27. // functional style
  28. object ChangeSign extends App {
  29.   def signChangeCount(list: List[Int]): Int = {
  30.     def f(list: List[Int], sum: Int, current: Int): Int = {
  31.       list match {
  32.         case Nil => sum
  33.         case head :: tail if head * current < 0 => f(tail, sum+1, head)
  34.         case head :: tail => f(tail, sum, current)
  35.       }
  36.     }
  37.  
  38.     f(list, 0, -list.headOption.getOrElse(0))    // we put "-" sign to count the first interval
  39.   }
  40.  
  41.  
  42.   println(signChangeCount(List.empty))                                    // 0
  43.   println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9)))                   // 3
  44.   println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9, -2, 5, -6, 0, 5)))  // 7
  45. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement