-
-
Save morteza/9dcfdf75bd2ba1683039ba8a1bc8203f to your computer and use it in GitHub Desktop.
Solution to scala-melb challenge, Mar 14 2012
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
// 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