2011-03-20 78 views

回答

0

有了這樣一個小小的種子和陣列,你需要用我的例子來創作。

正如Alex建議的那樣,他提供的網站有一個很好的隨機播放功能。我已經將它與另一個函數結合起來以獲得種子的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 

......其中 「出現」 隨機。我會建議大種子。

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));