Skip to content

Instantly share code, notes, and snippets.

@k-kinzal
Last active August 29, 2015 14:03
Show Gist options
  • Save k-kinzal/ec0c3b755d46466bf237 to your computer and use it in GitHub Desktop.
Save k-kinzal/ec0c3b755d46466bf237 to your computer and use it in GitHub Desktop.
Scala training
def binarySearch(number: Int, numbers: List[Int]): Try[Int] = {
import scala.annotation.tailrec
@tailrec
def recursive(number: Int, numbers: List[Int], left:Int = 0): Try[Int] = {
(numbers.length / 2) match {
case i if (numbers == Nil) || (numbers.length == 1 && numbers(i) != number) => Failure(new NoSuchElementException)
case i => numbers(i) match {
case n if n == number => Try{i + left}
case n if n > number => recursive(number, numbers.take(i), left)
case n if n < number => recursive(number, numbers.drop(i), left + i)
}
}
}
recursive(number, numbers, 0)
}
def countFruitsFromLines(lines: List[String]): Map[String, Int] = {
lines.flatMap(_.split(" ")).foldLeft(Map.empty[String, Int]) { (m, w) =>
m.updated(w, m.getOrElse(w, 0) + 1)
}
}
def fact(n: Int): Long = {
Range(1, math.max(n + 1, 2)).reduceLeft(_ * _)
}
def fact(n: Int): Long = {
def from(a: Long, b :Long): Stream[Long] = {
Stream.cons(b, from(a + 1, a * b))
}
from(1, 1).take(n + 1).last
}
def fib(n: Long): Long = {
def from(a: Long, b :Long): Stream[Long] = {
Stream.cons(a, from(b, a + b))
}
from(0, 1).take(n.toInt + 1).last
}
def getSum(numbers: List[Int]): Long = {
numbers.reduceLeft(_ + _)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment