Skip to content

Instantly share code, notes, and snippets.

@Megaprog
Last active March 18, 2016 07:06
Show Gist options
  • Save Megaprog/5812bcc08be043ec0da5 to your computer and use it in GitHub Desktop.
Save Megaprog/5812bcc08be043ec0da5 to your computer and use it in GitHub Desktop.
trait EnoughParticipants {
/** Given probabilities of each participant attending in "probabilities",
* calculate the probability that at least "needed" participants will participate.
*
* The probability has to be accurate to the precision of 0.001.
*/
def calculate(probabilities: List[Double], needed: Int): Double
}
class EnoughParticipantsImpl extends EnoughParticipants {
override def calculate(probabilities: List[Double], needed: Int): Double = {
roundTo001(combinations(probabilities, needed).foldLeft(0.0)((s, l) => probabilitySum(s, l.product)))
}
def combinations[T](list: List[T], elements: Int): List[List[T]] = {
if (list.size == elements)
List(list)
else if (elements == 1)
list.map(e => List(e))
else
combinations(list.tail, elements - 1).map(l => list.head :: l) ::: combinations(list.tail, elements)
}
def probabilitySum(p1: Double, p2: Double) = p1 + p2 - p1 * p2
def roundTo001(value: Double) = BigDecimal(value).setScale(3, BigDecimal.RoundingMode.HALF_UP).toDouble
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment