Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Task: given a list of Integers. Find a count of intervals with the same sign.
- // Example: f(List(4, 5, -4, -5, 4, 5)) shouldBe 3
- // imperative style
- object ChangeSign extends App {
- def signChangeCount(list: List[Int]): Int = {
- var sum = 0
- if (list.nonEmpty) {
- var current = -list.head // we put "-" sign to count the first interval
- for (i <- list) {
- if (i * current < 0) {
- sum += 1
- current = i
- }
- }
- }
- sum
- }
- println(signChangeCount(List.empty)) // 0
- println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9))) // 3
- println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9, -2, 5, -6, 0, 5))) // 7
- }
- // functional style
- object ChangeSign extends App {
- def signChangeCount(list: List[Int]): Int = {
- def f(list: List[Int], sum: Int, current: Int): Int = {
- list match {
- case Nil => sum
- case head :: tail if head * current < 0 => f(tail, sum+1, head)
- case head :: tail => f(tail, sum, current)
- }
- }
- f(list, 0, -list.headOption.getOrElse(0)) // we put "-" sign to count the first interval
- }
- println(signChangeCount(List.empty)) // 0
- println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9))) // 3
- println(signChangeCount(List(3, 6, 8, -2, -4, 8, 9, -2, 5, -6, 0, 5))) // 7
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement