给定一个数字,产生另一个每次都相同且与所有其他结果不同的随机数 [英] Given a number, produce another random number that is the same every time and distinct from all other results

查看:15
本文介绍了给定一个数字,产生另一个每次都相同且与所有其他结果不同的随机数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上,我想帮助设计一个算法,该算法采用给定的数字,并返回一个与第一个数字无关的随机数.规定是 a) 对于相似的输入编号,给定的输出编号将始终相同,并且 b) 在某个范围内(例如 1-100),所有输出编号都是不同的.即,100 以下的两个不同输入数字不会给出相同的输出数字.

Basically, I would like help designing an algorithm that takes a given number, and returns a random number that is unrelated to the first number. The stipulations being that a) the given output number will always be the same for a similar input number, and b) within a certain range (ex. 1-100), all output numbers are distinct. ie., no two different input numbers under 100 will give the same output number.

我知道通过创建一个有序的数字列表,随机排列它们,然后返回输入的索引很容易做到.但我想知道是否可以在没有任何缓存的情况下完成.也许使用某种散列算法?主要的原因是,如果可能的输出范围要大得多,比如 10000000000,那么生成整个范围的数字然后随机打乱它们将是可笑的,如果你只打算从中得到几个结果

I know it's easy to do by creating an ordered list of numbers, shuffling them randomly, and then returning the input's index. But I want to know if it can be done without any caching at all. Perhaps with some kind of hashing algorithm? Mostly the reason for this is that if the range of possible outputs were much larger, say 10000000000, then it would be ludicrous to generate an entire range of numbers and then shuffle them randomly, if you were only going to get a few results out of it.

不管它是用什么语言完成的,我只想知道它是否可能.这个问题我想了很久,除了我已经想到的解决方案之外,我想不出其他的解决方案.

Doesn't matter what language it's done in, I just want to know if it's possible. I've been thinking about this problem for a long time and I can't think of a solution besides the one I've already come up with.

我刚刚有了另一个想法;有另一种算法返回第一个算法的反向会很有趣.这是否可能将是一个有趣的探索挑战.

I just had another idea; it would be interesting to have another algorithm that returned the reverse of the first one. Whether or not that's possible would be an interesting challenge to explore.

推荐答案

这听起来像是一个不重复的随机数生成器.对此有几种可能的方法.

This sounds like a non-repeating random number generator. There are several possible approaches to this.

如本文章中所述,我们可以通过选择一个质数p来生成它们,并且满足p % 4 = 3足够大(大于输出范围内的最大值)和以这种方式生成它们:

As described in this article, we can generate them by selecting a prime number p and satisfies p % 4 = 3 that is large enough (greater than the maximum value in the output range) and generate them this way:

int randomNumberUnique(int range_len , int p , int x)
    if(x * 2 < p)
       return (x * x) % p
    else
       return p - (x * x) % p

对于[0, p)范围内的输入,该算法将覆盖[0, p)中的所有值.

This algorithm will cover all values in [0 , p) for an input in range [0 , p).

这篇关于给定一个数字,产生另一个每次都相同且与所有其他结果不同的随机数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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