2011-03-20 4 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

자바 스크립트 자체는이 기능을 제공하지 않습니다. RNG는 시드 할 수 없습니다. 사람이 취할 수있는 다른 접근 방법이 여전히 있습니다. 여기에 하나 있습니다. 시드가보다 커야 (또는 동일한 배열이 반환 됨) 이어야합니다.이 충분한 "임의성"을 위해 배열 크기보다 커야합니다.

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)); 
관련 문제