我想不出一个好办法来做这件事,如果可能的话,我会感激你的帮助!
恐怕我还没有任何代码可以发布,因为我还没有那么远。
我需要从0-999.范围内的3个(或更多)参数中生成一个值序列。
对于给定的输入,该值必须始终是相同的,但在上下边界之间必须具有公平的分布,这样才会出现随机性。
例如:
function (1, 1, 1) = 423
function (1, 1, 2) = 716
function (1, 2, 1) = 112这些必须是合理的快速生产,我的意思是,我应该能够在网页加载期间生成100-200,没有明显的延迟。
该方法必须可以在C#中执行,但也可以在JavaScript中执行,否则我可能会使用CRC32或MD5哈希算法。
如果有帮助,这将被用作过程生成例程的一部分。
我以前试过问这个问题,但我觉得我解释的质量很差,让我失望了。
如果这句话措辞不当,我很抱歉。如果是的话,请告诉我,我会尽力进一步解释的。
非常感谢您的帮助。
发布于 2013-08-12 13:39:45
使用维基中的Marsaglia生成器
public class SimpleMarsagliaRandom
{
private const uint original_w = 1023;
private uint m_w = original_w; /* must not be zero */
private uint m_z = 0; /* must not be zero, initialized by the constructor */
public SimpleMarsagliaRandom()
{
this.init(666);
}
public void init(uint z)
{
this.m_w = original_w;
this.m_z = z;
}
public uint get_random()
{
this.m_z = 36969 * (this.m_z & 65535) + (this.m_z >> 16);
this.m_w = 18000 * (this.m_w & 65535) + (this.m_w >> 16);
return (this.m_z << 16) + this.m_w; /* 32-bit result */
}
public uint get_random(uint min, uint max)
{
// max excluded
uint num = max - min;
return (this.get_random() % num) + min;
}
}和
simpleMarsagliaRandom = function()
{
var original_w = 1023 >>> 0;
var m_w = 0, m_z = 0;
this.init = function(z)
{
m_w = original_w;
m_z = z >>> 0;
};
this.init(666);
var internalRandom = function()
{
m_z = (36969 * (m_z & 65535) + (m_z >>> 16)) >>> 0;
m_w = (18000 * (m_w & 65535) + (m_w >>> 16)) >>> 0;
return (((m_z << 16) >>> 0) + m_w) >>> 0; /* 32-bit result */
};
this.get_random = function(min, max)
{
if (arguments.length < 2)
{
return internalRandom();
}
var num = ((max >>> 0) - (min >>> 0)) >>> 0;
return ((internalRandom() % num) + min) >>> 0;
}
};在Javascript中,所有的>>>都要强迫uint的号码
完全未经测试的
请注意,在get_random中所做的从x到y生成数字的操作是错误的。较低的数字会比较高的数字多一些。举个例子:假设你有一个标准的6面骰子。你翻开它,你就得到1-6。现在假设你在上面打印数字0-5。你翻开它,你就能得到0-5。没问题。但你需要0-3范围内的数字。所以你要滚% 3..。所以我们有:
rolled => rolled % 3
0 => 0,
1 => 1,
2 => 2,
3 => 0,
4 => 1,
5 => 2,
6 => 0. 0的结果更常见。
C#版本的Ideone:http://ideone.com/VQudcV
JSFiddle for Javascript版本:http://jsfiddle.net/dqayk/
发布于 2013-08-12 13:35:51
这里有一个:
function sequence(x, y, z) {
return Math.abs(441*x-311*y+293*z) % 1000;
}它甚至从您的示例中产生输出!
发布于 2013-08-12 13:40:30
您应该能够在MD5和JS中使用C#散列。
在C#中:
int Hash(params int[] values)
{
System.Security.Cryptography.MD5 hasher = MD5.Create();
string valuesAsString = string.Join(",", values);
var hash = hasher.ComputeHash(Encoding.UTF8.GetBytes(valuesAsString));
var hashAsInt = BitConverter.ToInt32(hash, 0);
return Math.Abs(hashAsInt % 1000);
}在JS中,使用一些MD5算法(例如jshash)实现相同的方法
https://stackoverflow.com/questions/18188191
复制相似问题