简单的伪随机算法 [英] Simple Pseudo-Random Algorithm

查看:244
本文介绍了简单的伪随机算法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要一个伪随机数生成器,该伪随机数生成器将一个数字作为输入并返回另一个数字,该数字是可复制的,并且似乎是随机的.

I'm need a pseudo-random generator which takes a number as input and returns another number witch is reproducible and seems to be random.

  • 每个输入数字应与一个输出数字完全匹配,反之亦然
  • 相同的输入数字始终会导致相同的输出数字
  • 紧靠在一起的顺序输入数字(例如1和2)应产生完全不同的输出数字(例如1 => 9783526,2 => 283)

它不一定是完美的,只是创建随机但可重现的测试数据.

It must not be perfect, it's just to create random but reproducible test data.

我使用C#.

前段时间,我写了一段有趣的代码,产生了一些随机性.

I wrote this funny piece of code some time ago which produced something random.

  public static long Scramble(long number, long max) 
  {
    // some random values 
    long[] scramblers = { 3, 5, 7, 31, 343, 2348, 89897 };
    number += (max / 7) + 6;
    number %= max;
    // shuffle according to divisibility
    foreach (long scrambler in scramblers) 
    {
      if (scrambler >= max / 3) break;
      number = ((number * scrambler) % max) 
        + ((number * scrambler) / max);
    }

    return number % max;
  }

我想要一种更好,更可靠的东西,可以处理任意大小的数字(无max参数).

I would like to have something better, more reliable, working with any size of number (no max argument).

这可以使用CRC算法解决吗?或一些混洗的东西.

Could this probably be solved using a CRC algorithm? Or some bit shuffling stuff.

推荐答案

您(也许)可以使用Random类在C#中轻松地做到这一点:

You (maybe) can do this easily in C# using the Random class:

public int GetPseudoRandomNumber(int input)
{
    Random random = new Random(input);
    return random.Next();
}

由于您在输入中明确植入了Random,因此每次输入相同的输入值时,您都会得到相同的输出.

Since you're explicitly seeding Random with the input, you will get the same output every time given the same input value.

这篇关于简单的伪随机算法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆