Skip to content

Instantly share code, notes, and snippets.

@emaxerrno
Created October 21, 2013 19:01
Show Gist options
  • Select an option

  • Save emaxerrno/7089113 to your computer and use it in GitHub Desktop.

Select an option

Save emaxerrno/7089113 to your computer and use it in GitHub Desktop.
randomclicker.scala
package com.yieldmo.simulation.actor
import akka.actor.{ Actor, ActorSystem, Props, ActorLogging }
import com.yieldmo.simulation.TrafficSimulationProtocol._
class RandomClick extends Actor with ActorLogging {
// uses 30K in memory per instance. Use wisely
// described http://www.iro.umontreal.ca/~lecuyer/myftp/papers/wellrng.pdf
// better than marsene twister
private val rand = new org.apache.commons.math3.random.Well44497b(scala.compat.Platform.currentTime)
def pickCreative(creatives: Array[Creative]): Option[Creative] = {
def tail(j: Int): Double = {
if (j < 0) 1.0
else (1 - creatives(j).ctr) * tail(j - 1)
}
val probabilities = creatives.zipWithIndex.map {
case (creative, i) =>
// p_i(head) * for all i --> do p_(i-1)(tail)
(creative, creative.ctr * tail(i - 1))
}
// pick a probability at random
val p = rand.nextDouble
probabilities.collectFirst { case (creative, probabilityOfClick) if p < probabilityOfClick => creative }
}
def receive = {
case arr: Array[Creative] =>
pickCreative(arr) foreach (sender ! _)
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment