Skip to content

Instantly share code, notes, and snippets.

@adamrabung
Last active August 29, 2015 14:03
Show Gist options
  • Save adamrabung/32c766a68ab28fbb811b to your computer and use it in GitHub Desktop.
Save adamrabung/32c766a68ab28fbb811b to your computer and use it in GitHub Desktop.
def weightedShuffle[T](ts: List[T], weight: T => Int): List[T] = {
case class ValueAndCumulativeWeight(t: T, cumWeight: Int)
@tailrec def weightedShuffle0(ts: List[T], weight: T => Int, acc: List[T]): List[T] = ts match {
case Nil => acc
case only :: Nil => acc :+ only
case head :: tail => {
val selection = Randoms.randomInt(0, ts.map(weight).sum)
val choice = tail
.scanLeft(ValueAndCumulativeWeight(head, weight(head)))((soFar, x) => ValueAndCumulativeWeight(x, soFar.cumWeight + weight(x)))
.find(_.cumWeight >= selection)
.get.t
weightedShuffle0(ts diff Seq(choice), weight, acc :+ choice)
}
}
weightedShuffle0(ts, weight, List.empty)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment