Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Created January 16, 2014 14:05
Show Gist options
  • Save MishaelRosenthal/8455514 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/8455514 to your computer and use it in GitHub Desktop.
The Birthday problem (paradox) implementation in Scala. http://en.wikipedia.org/wiki/Birthday_problem
package com.liveperson.predictivedialer.examples.misc
import scala.util.Random
import scala.collection.mutable
import com.liveperson.predictivedialer.common.utils.TraversableWithStatistics._
/**
* Created with IntelliJ IDEA.
* User: mishaelr
* Date: 1/16/14
* Time: 1:47 PM
*/
object BirthdayParadoxUntilSuccess extends App{
val rand = new Random()
require(args.length == 2,
"""Birthday Paradox: Usage: there should be two arguments:
|The total number of "days".
|The number of experiment repeats.""".stripMargin)
val (numOfDays, numOfRepeats) = (args(0).toInt, args(1).toInt)
val experimentsResults = List.fill(numOfRepeats)(numOfBirthdaysUntilCollision)
println(
"""Birthday Paradox: The mean number of birthdays until collision was %s, the variance was %s.
|The total number of "days" %s.
|The number of experiments was %s.
|sqrt(n) = %s""".format(experimentsResults.mean, experimentsResults.variance, numOfDays, numOfRepeats, math.sqrt(numOfDays)).stripMargin)
def numOfBirthdaysUntilCollision = {
val birthdayIterator = Iterator.continually(rand.nextInt(numOfDays)).zipWithIndex
val encounteredBirthdays = mutable.Set[Int]()
val firstCollision = birthdayIterator.find{case (birthday, index) => !(encounteredBirthdays add birthday)}
firstCollision.get._2 + 1 // The +1 is due to index to length
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment