代码之家  ›  专栏  ›  技术社区  ›  Liam

如何在JavaScript中洗牌字符串中的字符?

  •  36
  • Liam  · 技术社区  · 15 年前

    特别是,我要确保避免 Microsoft's Browser Choice 洗牌代码。也就是说,我想确保每个字母在每个可能的位置都有相同的结束概率。

    6 回复  |  直到 6 年前
        1
  •  75
  •   Community Mohan Dere    9 年前

    我修改了一个 Fisher-Yates Shuffle entry on Wikipedia 要随机播放字符串:

    String.prototype.shuffle = function () {
        var a = this.split(""),
            n = a.length;
    
        for(var i = n - 1; i > 0; i--) {
            var j = Math.floor(Math.random() * (i + 1));
            var tmp = a[i];
            a[i] = a[j];
            a[j] = tmp;
        }
        return a.join("");
    }
    console.log("the quick brown fox jumps over the lazy dog".shuffle());
    //-> "veolrm  hth  ke opynug tusbxq ocrad ofeizwj"
    
    console.log("the quick brown fox jumps over the lazy dog".shuffle());
    //-> "o dt hutpe u iqrxj  yaenbwoolhsvmkcger ozf "
    

    更多信息请参见 Jon Skeet's answer Is it correct to use JavaScript Array.sort() method for shuffling? .

        2
  •  38
  •   Joel Mellon    12 年前

    如果“真正的”随机性很重要,我建议不要这样做。请参阅下面的编辑。

    我只想添加一些我最喜欢的方法;)

    var str = "My bologna has a first name, it's O S C A R.";
    

    排成一行:

    var shuffled = str.split('').sort(function(){return 0.5-Math.random()}).join('');
    

    输出:

    oa, a si'rSRn f gbomi. aylt AtCnhO ass eM
    as'oh ngS li Ays.rC nRamsb Oo ait a ,eMtf
    y alCOSf e gAointsorasmn bR Ms .' ta ih,a
    

    他在下面链接的文章是一篇很好的阅读文章,但是解释了一个完全不同的用例,它会影响统计数据。我个人无法想象在字符串上使用这个“random”函数会有什么实际问题,但是作为一个编码人员,您有责任知道 用这个。

    我把这个留给了所有随机化的人。

        3
  •  8
  •   Maximilian Lindsey    8 年前

    尽管我已经回答了这个问题,但我还是想和大家分享我的解决方案:

    function shuffelWord (word){
        var shuffledWord = '';
        word = word.split('');
        while (word.length > 0) {
          shuffledWord +=  word.splice(word.length * Math.random() << 0, 1);
        }
        return shuffledWord;
    }
    
    // 'Batman' => 'aBmnta'
    

    你也可以 try it out (jsfiddle) .

        4
  •  1
  •   Ste    6 年前

    这里有一个洗牌词。

    下面是regex的解释: https://regex101.com/r/aFcEtk/1

    它也有一些有趣的结果。

    // Shuffles words
    // var str = "1 2 3 4 5 6 7 8 9 10";
    var str = "the quick brown fox jumps over the lazy dog A.S.A.P. That's right, this happened.";
    var every_word_im_shuffling = str.split(/\s\b(?!\s)/).sort(function(){return 0.5-Math.random()}).join(' ');
    console.log(every_word_im_shuffling);
        5
  •  0
  •   user1289673    12 年前
    String.prototype.shuffle=function(){
    
       var that=this.split("");
       var len = that.length,t,i
       while(len){
        i=Math.random()*len-- |0;
        t=that[len],that[len]=that[i],that[i]=t;
       }
       return that.join("");
    }
    
        6
  •  0
  •   Mayur Nandane    10 年前
                      shuffleString = function(strInput){
                         var inpArr = strInput.split("");//this will give array of input string
                         var arrRand = []; //this will give shuffled array
                         var arrTempInd = []; // to store shuffled indexes
                         var max = inpArr.length;
                         var min = 0;
                         var tempInd;
                         var i =0 ;
    
                          do{
                               tempInd = Math.floor(Math.random() * (max - min));//to generate random index between range
                               if(arrTempInd.indexOf(tempInd)<0){ //to check if index is already available in array to avoid repeatation
                                    arrRand[i] = inpArr[tempInd]; // to push character at random index
                                    arrTempInd.push(tempInd); //to push random indexes 
                                    i++;
                                }
                           }
                            while(arrTempInd.length < max){ // to check if random array lenght is equal to input string lenght
                                return arrRand.join("").toString(); // this will return shuffled string
                            }
                     };
    

    只需将字符串传递给函数,然后获取无序字符串

        7
  •  0
  •   Captain Fail    8 年前
    String.prototype.shuffle = function(){
      return this.split('').sort(function(a,b){
        return (7 - (Math.random()+'')[5]);
      }).join('');
    };
    
        8
  •  0
  •   Darkrum    7 年前

    对拼字的另一种看法。所有其他的答案经过足够的迭代后都会返回未分类的单词,而我的答案不会。

    var scramble = word => {
    
        var unique = {};
        var newWord = "";
        var wordLength = word.length;
    
        word = word.toLowerCase(); //Because why would we want to make it easy for them?
    
        while(wordLength != newWord.length) {
    
            var random = ~~(Math.random() * wordLength);
    
            if(
    
              unique[random]
              ||
              random == newWord.length && random != (wordLength - 1) //Don't put the character at the same index it was, nore get stuck in a infinite loop.
    
            ) continue; //This is like return but for while loops to start over.
    
            unique[random] = true;
            newWord += word[random];
    
        };
    
        return newWord;
    
    };
    
    scramble("God"); //dgo, gdo, ogd
    
        9
  •  0
  •   chickens    6 年前

    最短一行:

    let shuffled = str.split('').sort(()=>(Math.random()-0.5)).join('');
    
        10
  •  0
  •   Yevhen Horbunkov    6 年前

    又一个 Fisher-Yates 实施:

    const str = 'ABCDEFG',
    
          shuffle = str => 
            [...str]
              .reduceRight((res,_,__,arr) => (
                res.push(...arr.splice(0|Math.random()*arr.length,1)),
                res) ,[])
              .join('')
    
    console.log(shuffle(str))
    .as-console-wrapper{min-height:100%;}