refactor, implement LCG
LCG ... Linear Congruential Generator
This commit is contained in:
34
src/commonMain/kotlin/com/infendro/random/prng/LCG.kt
Normal file
34
src/commonMain/kotlin/com/infendro/random/prng/LCG.kt
Normal file
@@ -0,0 +1,34 @@
|
||||
package com.infendro.random.prng
|
||||
|
||||
import com.infendro.bytearray.padStart
|
||||
import com.infendro.bytearray.toUByteArray
|
||||
import com.infendro.bytearray.toULong
|
||||
import kotlin.math.min
|
||||
import kotlin.properties.Delegates
|
||||
|
||||
class LCG internal constructor() : PRNG() {
|
||||
private val a: ULong = 25214903917UL
|
||||
private val c: ULong = 11UL
|
||||
private val m: ULong = 1UL shl 48
|
||||
|
||||
private var x: ULong by Delegates.notNull()
|
||||
|
||||
override fun seed(
|
||||
seed: UByteArray,
|
||||
) {
|
||||
val s = seed.padStart(8, 0x00U).takeLast(8).toUByteArray()
|
||||
x = s.toULong() % m
|
||||
}
|
||||
|
||||
override fun generate(
|
||||
count: Int,
|
||||
): UByteArray {
|
||||
return buildList {
|
||||
while (size < count) {
|
||||
x = (a * x + c) % m
|
||||
|
||||
addAll(x.toUByteArray().takeLast(min(count - size, 6)))
|
||||
}
|
||||
}.toUByteArray()
|
||||
}
|
||||
}
|
||||
27
src/commonMain/kotlin/com/infendro/random/prng/PRNG.kt
Normal file
27
src/commonMain/kotlin/com/infendro/random/prng/PRNG.kt
Normal file
@@ -0,0 +1,27 @@
|
||||
package com.infendro.random.prng
|
||||
|
||||
import com.infendro.bytearray.toInt
|
||||
import kotlin.random.Random
|
||||
|
||||
abstract class PRNG : Random() {
|
||||
abstract fun seed(
|
||||
seed: UByteArray,
|
||||
)
|
||||
|
||||
abstract fun generate(
|
||||
count: Int,
|
||||
): UByteArray
|
||||
|
||||
override fun nextBits(
|
||||
bitCount: Int,
|
||||
): Int {
|
||||
if (bitCount !in 0..32) throw Exception()
|
||||
if (bitCount == 0) return 0
|
||||
|
||||
return generate(4).toInt() ushr (32 - bitCount)
|
||||
}
|
||||
|
||||
companion object {
|
||||
fun LCG() = com.infendro.random.prng.LCG()
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user