Created
March 24, 2015 14:10
-
-
Save shigemk2/0ccf3e304d0d7042946e to your computer and use it in GitHub Desktop.
This file contains 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
def findFirst1(ss: Array[String], key: String): Int = { | |
@annotation.tailrec | |
def loop(n: Int): Int = | |
if (n >= ss.length) -1 | |
else if (ss(n) == key) n | |
else loop(n + 1) | |
loop(0) | |
} | |
println(findFirst1(Array("a", "b", "c"), "a")) | |
def findFirst2[A](as: Array[A], p: A => Boolean): Int = { | |
@annotation.tailrec | |
def loop(n: Int): Int = | |
if (n >= as.length) -1 | |
else if (p(as(n))) n | |
else loop(n + 1) | |
loop(0) | |
} | |
println(findFirst2(Array("a", "b", "c"), (x: String) => x == "a")) | |
println(findFirst2(Array(1, 2, 3), (x: Int) => x == 1)) | |
def isSorted[A](as: Array[A], gt: (A,A) => Boolean): Boolean = { | |
@annotation.tailrec | |
def go(n: Int): Boolean = | |
if (n >= as.length-1) true | |
else if (gt(as(n), as(n+1))) false | |
else go(n+1) | |
go(0) | |
} | |
println(isSorted(Array(1, 2, 3), (x: Int, y: Int) => x > y)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment