简单的线性同余生成器(LCG)
可用于生成伪随机数,其算法是基于线性同余发生器。
应用场景:前端输入相同的数,生成随机数,不存库但是可以输出相同的结果,灵感来自Minecraft、
js
// seed:随机数种子
function seedRandom (seed) {
const m = 0x80000000 // 2^31
const a = 1103515245
const c = 12345
let seedValue = (typeof seed === 'string') ? seed.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) : seed
return function () {
seedValue = (a * seedValue + c) % m
return seedValue / m // 返回0到1之间的随机数
}
}
```// seed:随机数种子
function seedRandom (seed) {
const m = 0x80000000 // 2^31
const a = 1103515245
const c = 12345
let seedValue = (typeof seed === 'string') ? seed.split('').reduce((acc, char) => acc + char.charCodeAt(0), 0) : seed
return function () {
seedValue = (a * seedValue + c) % m
return seedValue / m // 返回0到1之间的随机数
}
}
```
liang14658fox