Instantly share code, notes, and snippets.

Embed
What would you like to do?
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)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment