-
-
Save Aivean/1364baae6fbdcb812f5b 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
package arsng | |
import scala.collection.mutable | |
import scala.collection.mutable.ListBuffer | |
import scala.util.Random | |
object GroupTest2 extends App { | |
val r = new Random(1234) | |
val myList = (0 to 1000000).map(_ => r.nextInt(10000)).toList | |
val thresh = 3 | |
def measure(iterations:Int)(x: => Unit) = { | |
val times = new ListBuffer[Long] | |
for (i <- 0 to iterations) { | |
val time = System.currentTimeMillis() | |
x | |
if (i > iterations / 3) { | |
times += (System.currentTimeMillis() - time) | |
} | |
} | |
times.sum / times.size | |
} | |
def authSolve = { | |
myList.foldLeft(Map[Int,Int]()){case(m, i) => m + (i -> (m.getOrElse(i, 0) + 1))}.filter(_._2 >= thresh).keys | |
} | |
def ixxSolve = { | |
val tuple = (Map[Int, Int](), List[Int]()) | |
val res = myList.foldLeft(tuple) { | |
case ((m, s), i) => | |
val count = m.getOrElse(i, 0) + 1 | |
(m + (i -> count), if (count == thresh) i :: s else s) | |
} | |
res._2 | |
} | |
def ixxSolve2 = { | |
val tuple = (Map[Int, Int](), List[Int]()) | |
val res = myList.foldLeft(tuple) { | |
case ((m, s), i) => | |
val count = m.getOrElse(i, 0) + 1 | |
(if (count <= 3) m + (i -> count) else m, if (count == thresh) i :: s else s) | |
} | |
res._2 | |
} | |
def mySolve = { | |
val map = new mutable.HashMap[Int, Int]() | |
val res = new ListBuffer[Int] | |
myList.foreach { | |
i => | |
val c = map.getOrElse(i, 0) + 1 | |
if (c == thresh) { | |
res += i | |
} | |
if (c <= thresh) { | |
map(i) = c | |
} | |
} | |
res | |
} | |
println("Authors solution") | |
println(measure(20) { | |
authSolve | |
}) | |
println("Ixx solution: ") | |
println(measure(20) { | |
ixxSolve | |
}) | |
println("Ixx solution2 (eliminated excessive map writes): ") | |
println(measure(20) { | |
ixxSolve2 | |
}) | |
println("My solution: ") | |
println(measure(20) { | |
mySolve | |
}) | |
println(mySolve.toSet == ixxSolve.toSet) | |
println(mySolve.toSet == authSolve.toSet) | |
println(ixxSolve.toSet == authSolve.toSet) | |
println(ixxSolve2.toSet == authSolve.toSet) | |
} | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment