Created
December 14, 2013 04:15
-
-
Save goldeneggg/7955620 to your computer and use it in GitHub Desktop.
scala コップ本の自作distinctよりもちょっと速い自作distinct
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 ssbt | |
object HogeMain { | |
def main(args: Array[String]) { | |
val list = getRandomList(50, 500) | |
println("----- start distinct1") | |
repeat(10, repeatDistinct(distinct1[Int], list)) | |
println("----- start distinct2") | |
repeat(10, repeatDistinct(distinct2[Int], list)) | |
} | |
def repeat(num: Int, f: => Unit) { | |
var start: Long = 0L | |
var end: Long = 0L | |
var sec: Long = 0L | |
(1 to num).foreach { i => | |
start = System.currentTimeMillis | |
f | |
end = System.currentTimeMillis | |
sec = end - start | |
println("Total millisec: " + sec) | |
} | |
} | |
def repeatDistinct(f: List[Int] => List[Int], list: List[Int]) { | |
(1 to 1000).foreach { i => | |
val l = f(list) | |
//val l = f(list).sorted | |
//println(l) | |
} | |
} | |
// filterを使わずcontainsで重複判定(速い) | |
def distinct1[A](xs: List[A]): List[A] = { | |
xs match { | |
case h :: t => { | |
if (t.contains(h)) distinct1(t) | |
else h :: distinct1(t) | |
} | |
case isEmpty => xs | |
} | |
} | |
// コップ本バージョン(遅い) | |
def distinct2[A](xs: List[A]): List[A] = { | |
if (xs.isEmpty) xs | |
else | |
xs.head :: distinct2(xs.tail.filter(x => x != xs.head)) | |
} | |
import scala.util.Random | |
def getRandomList(max: Int, length: Int): List[Int] = { | |
val r = new Random | |
(1 to length).map(i => r.nextInt(max)).toList | |
} | |
} |
Author
goldeneggg
commented
Dec 14, 2013
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment