Kotlin Random
import kotlin.math.floor | |
/** | |
* This class implement a Linear Congruential Generator. | |
* | |
* @author Valentin Michalak | |
*/ | |
class Random(private var seed: Long = 0) { | |
companion object { | |
private val mask: Long = (1L shl 48) - 1 | |
private val multiplier: Long = 25214903917 | |
private val increment: Long = 11 | |
} | |
/** | |
* @param bitCount (Max 48) | |
*/ | |
private fun next(bitCount: Int): Int { | |
seed = (multiplier * seed + increment) and mask | |
return seed.ushr(48 - bitCount).toInt() | |
} | |
fun nextBoolean(): Boolean = next(1) != 0 | |
fun nextDouble(): Double = ((next(26).toLong() shl 27) + next(27)) / (1L shl 53).toDouble() | |
fun nextFloat(): Float = next(24) / (1 shl 24).toFloat() | |
fun nextInt(): Int = next(32) | |
fun nextInt(range: IntRange): Int = floor(nextDouble() * (1 + range.last - range.first)).toInt() + range.first | |
fun nextLong(): Long = (next(32).toLong() shl 32) + next(32) | |
} |
This comment has been minimized.
This comment has been minimized.
@BOPOH if you are in a Kotlin Multiplatform context ThreadLocalRandom doesn't work. |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This comment has been minimized.
I think it's better to use ThreadLocalRandom in Kotlin < 1.3