Created
January 4, 2018 09:59
-
-
Save vmichalak/11e5ddb567786af0ed1ae4d7f57441d4 to your computer and use it in GitHub Desktop.
Kotlin Random
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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
I think it's better to use ThreadLocalRandom in Kotlin < 1.3