Skip to content

Instantly share code, notes, and snippets.

@morteza
Forked from TJC/weighted_random.scala
Created May 31, 2018 14:10
Show Gist options
  • Save morteza/9dcfdf75bd2ba1683039ba8a1bc8203f to your computer and use it in GitHub Desktop.
Save morteza/9dcfdf75bd2ba1683039ba8a1bc8203f to your computer and use it in GitHub Desktop.
Solution to scala-melb challenge, Mar 14 2012
// This is a fairly ugly solution; in a hurry and didn't spend much time on it.
import scala.util.Random
case class WeightedItem[T](item: T, weight: Double)
val items = Seq(WeightedItem("Red", 1d/6), WeightedItem("Blue", 2d/6),
WeightedItem("Green", 3d/6) )
def weightedSelection[T](
items: Seq[WeightedItem[T]],
numSelections: Int,
r: Random
): Seq[T] = {
val totalWeight = items.map(_.weight).sum
def pick_one: T = {
var rnd = r.nextDouble * totalWeight
for (i <- items) {
if (i.weight < rnd) {
return i.item
}
rnd = rnd - i.weight
}
// the above should always return something, but compiler doesn't
// realise that, hence this:
return items.head.item
}
for (i <- 1 to numSelections) yield pick_one
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment