Last active
June 2, 2022 16:35
-
-
Save cacilhas/0e0aa9e0968d3efc522fe206e14fe5b0 to your computer and use it in GitHub Desktop.
Real random generator
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 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 |
Author
cacilhas
commented
Apr 21, 2020
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment