Skip to content

Instantly share code, notes, and snippets.

@nuintun
Created May 25, 2020 02:30
Show Gist options
  • Select an option

  • Save nuintun/eac3bf75c5496f8acfe4e651842eca20 to your computer and use it in GitHub Desktop.

Select an option

Save nuintun/eac3bf75c5496f8acfe4e651842eca20 to your computer and use it in GitHub Desktop.
线性同余随机数
/**
* @function LCGRandom
* @description 线性同余随机数
* @param {number} seed
* @returns {number}
* @see https://gist.github.com/Protonk/5389384
*/
function LCGRandom1(seed = 0) {
return ((seed * 11 + 17) % 25) / 25;
}
/**
* @function LCGRandom
* @description 线性同余随机数
* @param {number} seed
* @returns {number}
* @see https://www.zhihu.com/question/22818104
*/
function LCGRandom2(seed = 0) {
return ((seed * 9301 + 49297) % 233280) / 233280;
}
@nuintun
Copy link
Author

nuintun commented Oct 14, 2025

/**
 * @function FeistelRandom
 * @description 使用 Feistel 网络实现的 16 位伪随机置换函数
 * @param {number} seed 输入值 (0-0xffff)
 * @returns {number} 输出的置换值 (0-0xffff)
 */
function FeistelRandom(seed: number): number {
  // Feistel网络轮数
  const rounds = 3;

  // 将16位分为左右两部分:高8位和低8位
  let left = seed >> 8;
  let right = seed & 0xff;

  // 执行多轮Feistel变换
  for (let round = 0; round < rounds; round++) {
    // 保存右半部分
    const nextLeft = right;

    // 使用轮函数 F(right, round) 与左半部分进行 XOR 运算
    // 轮函数: (right * 0x5d + round) & 0xff
    right = left ^ ((right * 0x5d + round) & 0xff);

    // 左右交换
    left = nextLeft;
  }

  // 合并左右两部分并返回结果
  return ((left << 8) | right) & 0xffff;
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment