Skip to content

Instantly share code, notes, and snippets.

@MishaelRosenthal
Created January 16, 2014 14:03
Show Gist options
  • Save MishaelRosenthal/8455488 to your computer and use it in GitHub Desktop.
Save MishaelRosenthal/8455488 to your computer and use it in GitHub Desktop.
The Coupon collector's problem implementation in Scala: http://en.wikipedia.org/wiki/Coupon_collector's_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 CouponCollectorUntilSuccess extends App{
val rand = new Random()
require(args.length == 2,
"""Coupon Collector: Usage: there should be two arguments:
|The total number of possible coupons.
|The number of experiment repeats.""".stripMargin)
val (totalNumCoupons, numOfRepeats) = (args(0).toInt, args(1).toInt)
val experimentsResults = List.fill(numOfRepeats)(collectCouponsUntilSuccess)
println(
"""Coupon Collector: The mean number of collected coupons until success was %s, the variance was %s.
|The total number of possible coupons %s.
|The number of experiments was %s.
|nlog(n) = %s""".format(experimentsResults.mean, experimentsResults.variance, totalNumCoupons, numOfRepeats, totalNumCoupons * math.log(totalNumCoupons)).stripMargin)
def collectCouponsUntilSuccess = {
val couponsIterator = Iterator.continually(rand.nextInt(totalNumCoupons)).zipWithIndex
val collectedCoupons = mutable.Set[Int]()
val firstCouponOfSuccess = couponsIterator.find{case (coupon, index) =>
collectedCoupons += coupon
collectedCoupons.size == totalNumCoupons
}
firstCouponOfSuccess.get._2 + 1 //th +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