Skip to content

Instantly share code, notes, and snippets.

@cacilhas
Last active June 2, 2022 16:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save cacilhas/0e0aa9e0968d3efc522fe206e14fe5b0 to your computer and use it in GitHub Desktop.
Save cacilhas/0e0aa9e0968d3efc522fe206e14fe5b0 to your computer and use it in GitHub Desktop.
Real random generator
import java.io.IOException
import scala.io.Source
import scala.util.Random
case class RealRandom(val limit: Int) extends Iterator[Int]:
private val cacheSize = 128
private val url = s"https://www.random.org/integers/?num=$cacheSize&min=0&max=${limit-1}&col=1&base=10&format=plain&rnd=new"
private var generator = Iterator[Int]()
private lazy val failsafe = new Random(System.currentTimeMillis)
def next: Int =
if !generator.hasNext
then
try
generator = Source.fromURL(url).getLines map {_.toInt}
catch
case _: IOException ⇒ generator = fallback
generator.next
def hasNext: Boolean = true
private def fallback: Iterator[Int] =
(for (_ <- 1 until cacheSize) yield (failsafe.nextDouble * limit).toInt).iterator
@cacilhas
Copy link
Author

cacilhas commented Apr 21, 2020

Example:

for (i <- RealRandom(100) take 5) System.out println i.toString

@cacilhas
Copy link
Author

That’s the problem with randomness: you can never be sure.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment