Created
March 10, 2014 22:49
-
-
Save luiscubal/9476082 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package helloworld | |
import scala.collection.immutable.LinearSeq | |
import scala.annotation.tailrec | |
import scala.util.Random | |
import scala.collection.mutable.MutableList | |
import scala.collection.immutable.Queue | |
object HelloWorld { | |
def getArray() : Array[Int] = { | |
val ar = new Array[Int](20000) | |
for (i <- 0 until ar.length) { | |
ar(i) = i | |
} | |
ar | |
} | |
def getList() : LinearSeq[Int] = { | |
var lst = Queue[Int]() | |
for (i <- 0 until 20000) { | |
lst = lst.enqueue(-i) | |
} | |
lst | |
} | |
def main(args: Array[String]) = { | |
val array = getList() | |
val now = System.nanoTime | |
val result = isSorted2(array, (x: Int, y: Int) => x < y) | |
val elapsedTime = System.nanoTime - now | |
println(result) | |
println("Took %d ms.".format(elapsedTime / 1000000)) | |
} | |
def isSorted1[A](items: Array[A], cond: (A, A) => Boolean): Boolean = items match { | |
case Array(_) => true | |
case Array(x, y) => cond(x, y) | |
case Array(_*) => cond(items(0), items(1)) && isSorted1(items tail, cond) | |
} | |
@tailrec // remind the compiler that the recursion can be eliminated | |
def isSorted2[A](items: LinearSeq[A], cond: (A, A) => Boolean): Boolean = items match { | |
case Seq() => true // you forgot to handle empty input! | |
case Seq(_) => true | |
case x :: tail => cond(x, tail.head) && isSorted2(tail, cond) | |
} | |
def isSorted3[A](items: Iterable[A], cond: (A, A) => Boolean): Boolean = | |
items.isEmpty || (items zip items.tail forall (pair => cond(pair._1, pair._2))) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment