Created
April 7, 2014 05:37
-
-
Save robertsosinski/10015299 to your computer and use it in GitHub Desktop.
Generating factorial numbers with parallel processing using Akka
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
import akka.actor.{Actor, ActorLogging, ActorSystem, Props} | |
object Factorial extends App { | |
val factorials = List(200000, 180000, 320000, 280000, 220000, 420000, 550000, 480000) | |
val system = ActorSystem("factorial") | |
val collector = system.actorOf(Props(new FactorialCollector(factorials)), "fac-coll") | |
system.awaitTermination() | |
} | |
class FactorialCollector(list: List[Int]) extends Actor with ActorLogging { | |
var result: List[BigInt] = Nil | |
var size = list.size | |
for (num <- list) { | |
context.actorOf(Props(new FactorialCalculator), s"fac-$num") ! num | |
} | |
def receive = { | |
case num: BigInt => { | |
result = num :: result | |
size -= 1 | |
if (size == 0) { | |
log.info("DONE!") | |
context.system.shutdown() | |
} | |
} | |
} | |
} | |
class FactorialCalculator extends Actor with ActorLogging { | |
def receive = { | |
case number: Int => sender ! factor(number) | |
} | |
private def factor(n: Int) = factorTail(n, 1) | |
private def factorTail(num: Int, acc: BigInt): BigInt = { | |
(num, acc) match { | |
case (0, a) => a | |
case (n, a) => factorTail(n - 1, n * a) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment