Created
October 25, 2016 16:20
-
-
Save szeiger/f0483fd363282afdbb141b6c3b76732c 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
def find(a: Array[Array[Int]], v: Int): (Int, Int) = { | |
var i = 0 | |
while(i < a.length) { | |
val aa = a(i) | |
var j = 0 | |
while(j < aa.length) { | |
if(aa(j) == v) return (i, j) | |
j += 1 | |
} | |
i += 1 | |
} | |
null | |
} | |
def find2(a: Array[Array[Int]], v: Int): (Int, Int) = { | |
def f(i: Int): (Int, Int) = { | |
if(i < a.length) { | |
val aa = a(i) | |
def g(j: Int): (Int, Int) = { | |
if(j < aa.length) { | |
if(aa(j) == v) (i, j) else g(j+1) | |
} else null | |
} | |
val r = g(0) | |
if(r ne null) r else f(i+1) | |
} else null | |
} | |
f(0) | |
} | |
case object Escape extends RuntimeException with scala.util.control.NoStackTrace | |
def find3(a: Array[Array[Int]], v: Int): (Int, Int) = { | |
var x, y = 0 | |
try { | |
var i = 0 | |
while(i < a.length) { | |
val aa = a(i) | |
var j = 0 | |
while(j < aa.length) { | |
if(aa(j) == v) { | |
x = i | |
y = j | |
throw Escape | |
} | |
j += 1 | |
} | |
i += 1 | |
} | |
null | |
} catch { | |
case Escape => (x, y) | |
} | |
} | |
val a = Array(Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(1,2,3), Array(42)) | |
var i = 0 | |
while(i < 20) { | |
val t0 = System.currentTimeMillis | |
var c = 0 | |
var r: AnyRef = null | |
while(c < 10000000) { | |
r = find2(a, 42) | |
c += 1 | |
} | |
val t1 = System.currentTimeMillis | |
println(t1-t0) | |
i += 1 | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment