Skip to content

Instantly share code, notes, and snippets.

@vmichalak vmichalak/Random.kt
Created Jan 4, 2018

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)
}
@bopoh13

This comment has been minimized.

Copy link

commented Jul 25, 2019

I think it's better to use ThreadLocalRandom in Kotlin < 1.3

@vmichalak

This comment has been minimized.

Copy link
Owner Author

commented Jul 29, 2019

@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
You can’t perform that action at this time.