Skip to content

Instantly share code, notes, and snippets.

@vmichalak
Created January 4, 2018 09:59
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save vmichalak/11e5ddb567786af0ed1ae4d7f57441d4 to your computer and use it in GitHub Desktop.
Save vmichalak/11e5ddb567786af0ed1ae4d7f57441d4 to your computer and use it in GitHub Desktop.
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)
}
@h8nor
Copy link

h8nor commented Jul 25, 2019

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

@vmichalak
Copy link
Author

@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