我有一个javascript数组,我想根据我指定的数字或字符串进行排序。我希望数组看起来是随机排序的,但是如果输入是“6543”,那么数组的排序总是相同的。
答案 0 :(得分:3)
Javascript本身不提供此功能 - 其RNG无法播种。仍然可以采取不同的方法。这是一个。种子必须大于1(或将返回相同的数组),并且应大于数组大小以获得足够的“随机性”。
Array.prototype.deterministicShuffle=function(seed){
// A little error handling, whynot!
if(!seed)
throw new Error("deterministicShuffle: seed not given, or 0");
var temp,j;
for(var i=0; i<this.length; i++){
// Select a "random" position.
j = (seed % (i+1) + i) % this.length;
// Swap the current element with the "random" one.
temp=this[i];
this[i]=this[j];
this[j]=temp;
}
return this;
}
// Try it out, Aaron!
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6543));
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6544));
alert([0,1,2,3,4,5,6,7,8,9].deterministicShuffle(6545));
答案 1 :(得分:2)
使用a shuffle function并将Math.random()
替换为a random number generator where you can set your own seed。
然后将种子设置为输入数字。
答案 2 :(得分:0)
使用这么小的种子和数组,你需要通过我的例子获得创意。
正如亚历克斯所说,他提供的网站有一个很好的随机播放功能。我把它与另一个函数结合起来得到种子的ascii值。
您应该强烈考虑更改我的示例以对输入进行哈希处理。否则会发生很多碰撞。
以下是代码:
<script>
// http://sharkysoft.com/tutorials/jsa/content/018.html
function ascii_value (c)
{
// restrict input to a single character
c = c . charAt (0);
// loop through all possible ASCII values
var i;
for (i = 0; i < 256; ++ i)
{
// convert i into a 2-digit hex string
var h = i . toString (16);
if (h . length == 1)
h = "0" + h;
// insert a % character into the string
h = "%" + h;
// determine the character represented by the escape code
h = unescape (h);
// if the characters match, we've found the ASCII value
if (h == c)
break;
}
return i;
}
// http://snippets.dzone.com/posts/show/849
shuffle = function(o,seed){ //v1.0
for(var j, x, i = o.length; i; j = parseInt(seed / (o.length * 255) * i), x = o[--i], o[i] = o[j], o[j] = x);
return o;
};
function seedSort (string){
var charList = string.split('');
var seedValue = 0;
for(var i in charList){
seedValue += ascii_value(charList[i]);
}
return seedValue;
}
document.write(shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],seedSort("bob")));
document.write("<br>");
document.write(shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],seedSort("steve")));
document.write("<br>");
document.write(shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],seedSort("david's house")));
document.write("<br>");
document.write(shuffle([0, 1, 2, 3, 4, 5, 6, 7, 8, 9],seedSort("acorn22")));
</script>
这将产生
8,2,3,4,5,6,7,0,9,1
4,9,3,0,5,6,7,8,1,2
8,0,6,1,5,2,7,3,9,4
4,8,3,0,5,6,7,1,9,2
......随机“出现”。我会建议大种子。