Skip to content

Instantly share code, notes, and snippets.

@fada21
Last active August 6, 2016 16:48
Show Gist options
  • Save fada21/b2ce4a97949ad898a03c to your computer and use it in GitHub Desktop.
Save fada21/b2ce4a97949ad898a03c to your computer and use it in GitHub Desktop.
scala snippets
val line2nums = io.StdIn.readLine.split(" ").map(_.toInt)
val lines2nums = io.Source.stdin.getLines().map(_.toInt)
val streamOfInts = Stream.continually(io.StdIn.readInt())
val fib = {
def f(f0:Int, f1:Int): Stream[Int] = f0 #:: f(f1, f0 + f1)
f(0,1)
}
//fib(18)
//fib.take(19).toList
def quicksort[T <% Ordered[T]](list:List[T]): List[T] =
list match {
case Nil => Nil
case x :: xs =>
val (before,after) = xs partition (_ < x)
quicksort(before) ++ (x :: quicksort(after))
}
// or just use Scala utility for Arrays
val arr = Array(3,5,3,8)
scala.util.Sorting.quickSort(arr)
def binarySearch[A <% Ordered[A]](a: IndexedSeq[A], v: A) = {
@tailrec
def recurse(low: Int, high: Int): Option[Int] = (low + high) / 2 match {
case _ if high < low => None
case mid if a(mid) > v => recurse(low, mid - 1)
case mid if a(mid) < v => recurse(mid + 1, high)
case mid => Some(mid)
}
recurse(0, a.size - 1)
}
// same as above using java Arrays implementation (only for Arrays)
val a = Array(1,2,3,4)
java.util.Arrays.binarySearch(a, 2)
// or better new Searching
import scala.collection.Searching._
val l = List(1, 2, 3, 4, 5)
l.search(3)
def gcd(a: Int, b: Int): Int = if (b == 0) a else gcd(b, a % b)
//source @ http://abbi-gaurav.github.io/Scala-putting-the-pieces-together/
object PerfMeasures {
case class Stats[T](result: T, averageTime: Double, stdDev: Double) {
override def toString = s"function computes result: +$result " +
s"in $averageTime ms on average with standard deviation $stdDev"
}
def getStats[O](f: => O, n: Int = 5): Stats[O] = {
assert(n > 1)
def compute: (O, Double) = {
val t1 = System.nanoTime().toDouble
val res = f
val t2 = System.nanoTime().toDouble
(res, (t2 - t1) / 1e6)
}
val (results, times) = (1 to n + 5).map(x => compute).drop(5).unzip
val avgTime = times.reduceLeft(_ + _) / times.size
val stdDev = standardDeviation(avgTime, times)
Stats(results.head, avgTime, stdDev)
}
def standardDeviation(average: Double, list: Seq[Double]) = list match {
case Nil => 0.0
case _ =>
math.sqrt(list.foldLeft(0.0) {
case (acc, x) => acc + math.pow(x - average, 2)
} / list.length)
}
def publishPerformanceData[O](f: => O, n: Int = 5): Unit = {
val stats = getStats(f, n)
println(stats)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment