Files
prng.kt/src/commonMain/kotlin/com/infendro/random/prng/LCG.kt
Infendro feecfa49b9 refactor, implement LCG
LCG ... Linear Congruential Generator
2025-11-10 18:52:19 +01:00

35 lines
862 B
Kotlin

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()
}
}