Last active
August 29, 2015 14:03
-
-
Save adamrabung/32c766a68ab28fbb811b 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
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