Abhishek Kumar Abhishek Kumar - 9 months ago 45
Scala Question

How to make following code run for large values of `n` while maintaining the functional style in Scala?

Seq.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4

Basically this scala code checks number of times a random points comes out of first quadrant of a unit circle. For large values of
this code gives memory limit exceeded error as it requires too big sequence. I can write this java way. But is there some functional way to achieve this task?

Answer Source

If you use an Iterator no intermediate collection has to be created in memory.

Iterator.fill(n)(math.pow(Random.nextFloat,2) + math.pow(Random.nextFloat,2)).filter(_<1).size.toFloat/n*4