Skip to content

Instantly share code, notes, and snippets.

@hisui
Created January 12, 2016 03:38
Show Gist options
  • Save hisui/3648d1769ef3d45a196c to your computer and use it in GitHub Desktop.
Save hisui/3648d1769ef3d45a196c to your computer and use it in GitHub Desktop.
import scala.collection.immutable.SortedMap
import scala.util.Random
class WRR[+A](total: Int, map: SortedMap[Int, A]) {
require(!map.isEmpty)
def pick(rand: Random): A = map.until(rand.nextInt(total) + 1).last._2
}
object WRR {
def apply[A](e: (Int, A), a: (Int, A) *): WRR[A] = {
var sum = 0
val map = SortedMap((e +: a).map { case (w, e) => try sum -> e finally sum += w } :_*)
new WRR(sum, map)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment