×

Welcome to TagMyCode

Please login or create account to add a snippet.
0
0
 
0
Language: Text
Posted by: osocron coder
Added: Sep 13, 2016 4:22 PM
Views: 4
Functional pure counter implementation
  1. object CounterBlock extends App {
  2.  
  3.   def mCount(iter: Int): Int = {
  4.  
  5.     val randomX = new Random
  6.     val randomY = new Random
  7.  
  8.     def counterLoop[T](limit: Int, res: Int)(b: => T)(p: T => Boolean): Int = {
  9.       if (limit == 0) res
  10.       else if (p(b)) counterLoop(limit - 1, res + 1)(b)(p)
  11.       else counterLoop(limit - 1, res)(b)(p)
  12.     }
  13.  
  14.     def sumRandomPowers: Double = {
  15.       val x = randomX.nextDouble()
  16.       val y = randomY.nextDouble()
  17.       x*x + y*y
  18.     }
  19.  
  20.     counterLoop(iter, 0)(sumRandomPowers)(d => d < 1)
  21.  
  22.   }
  23.  
  24.   def monteCarloPiSeq(iter: Int): Double = 4.0 * mCount(iter) / iter
  25.  
  26.   println(monteCarloPiSeq(20000000))
  27.  
  28. }