2020-08-18 13:31:32 -06:00
|
|
|
package lila.common
|
|
|
|
|
2020-08-18 17:24:28 -06:00
|
|
|
import scala.collection.mutable.StringBuilder
|
2020-08-18 13:31:32 -06:00
|
|
|
|
2021-06-24 05:08:23 -06:00
|
|
|
abstract class Random {
|
2021-06-24 09:52:06 -06:00
|
|
|
|
2021-06-24 05:08:23 -06:00
|
|
|
protected def current: java.util.Random
|
2020-08-19 00:51:16 -06:00
|
|
|
|
2021-06-24 09:52:06 -06:00
|
|
|
def nextBoolean(): Boolean = current.nextBoolean()
|
|
|
|
def nextDouble(): Double = current.nextDouble()
|
|
|
|
def nextFloat(): Float = current.nextFloat()
|
|
|
|
def nextInt(): Int = current.nextInt()
|
|
|
|
def nextInt(n: Int): Int = current.nextInt(n)
|
|
|
|
def nextLong(): Long = current.nextLong()
|
|
|
|
def nextGaussian(): Double = current.nextGaussian()
|
2021-06-24 05:08:23 -06:00
|
|
|
|
2021-06-24 05:18:14 -06:00
|
|
|
def nextBytes(len: Int): Array[Byte] = {
|
|
|
|
val bytes = new Array[Byte](len)
|
|
|
|
current.nextBytes(bytes)
|
|
|
|
bytes
|
|
|
|
}
|
|
|
|
|
2021-06-24 05:08:23 -06:00
|
|
|
private def nextAlphanumeric(): Char = {
|
|
|
|
val chars = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
|
|
|
|
chars charAt nextInt(chars.length) // Constant time
|
|
|
|
}
|
|
|
|
|
2020-08-18 13:31:32 -06:00
|
|
|
def nextString(len: Int): String = {
|
|
|
|
val sb = new StringBuilder(len)
|
2021-06-24 05:08:23 -06:00
|
|
|
for (_ <- 0 until len) sb += nextAlphanumeric()
|
2020-08-18 13:31:32 -06:00
|
|
|
sb.result()
|
|
|
|
}
|
2021-06-24 05:08:23 -06:00
|
|
|
|
|
|
|
def shuffle[T, C](xs: IterableOnce[T])(implicit bf: scala.collection.BuildFrom[xs.type, T, C]): C =
|
|
|
|
new scala.util.Random(current).shuffle(xs)
|
|
|
|
|
2020-11-27 08:24:53 -07:00
|
|
|
def oneOf[A](vec: Vector[A]): Option[A] =
|
|
|
|
vec.nonEmpty ?? {
|
|
|
|
vec lift nextInt(vec.size)
|
|
|
|
}
|
2021-11-07 01:21:29 -07:00
|
|
|
|
|
|
|
// odds(1) = 100% true
|
|
|
|
// odds(2) = 50% true
|
|
|
|
// odds(3) = 33% true
|
|
|
|
def odds(n: Int): Boolean = nextInt(n) == 0
|
2020-08-18 13:31:32 -06:00
|
|
|
}
|
2021-06-24 05:08:23 -06:00
|
|
|
|
|
|
|
object ThreadLocalRandom extends Random {
|
|
|
|
override def current = java.util.concurrent.ThreadLocalRandom.current
|
2021-11-30 13:44:14 -07:00
|
|
|
|
|
|
|
def nextLong(n: Long): Long = current.nextLong(n)
|
2021-06-24 05:08:23 -06:00
|
|
|
}
|
|
|
|
|
|
|
|
object SecureRandom extends Random {
|
2021-06-24 05:20:33 -06:00
|
|
|
override val current = new java.security.SecureRandom()
|
2021-06-24 05:08:23 -06:00
|
|
|
}
|