Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I shuffle the characters in a string in JavaScript?

In particular, I want to make sure to avoid the mistake made in Microsoft's Browser Choice shuffle code. That is, I want to make sure that each letter has an equal probability of ending up in each possible position.

e.g. Given "ABCDEFG", return something like "GEFBDCA".

like image 751
Liam Avatar asked Oct 15 '10 15:10

Liam


People also ask

How do I randomize a character in a string in JavaScript?

random() method is used to generate random characters from the specified characters (A-Z, a-z, 0-9). The for loop is used to loop through the number passed into the generateString() function. During each iteration, a random character is generated.

Can you manipulate a string in JavaScript?

While JavaScript has many applications, working with string values is one of the most popular. Strings are objects within the JavaScript language. They are not stored as character arrays, so built-in functions must be used to manipulate their values.

How do you isolate the first character in a string JavaScript?

You should use the charAt() method, at index 0, to select the first character of the string. NOTE: charAt is preferable than using [ ] (bracket notation) as str. charAt(0) returns an empty string ( '' ) for str = '' instead of undefined in case of ''[0] .


3 Answers

I modified an example from the Fisher-Yates Shuffle entry on Wikipedia to shuffle strings:

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 "

More information can be found in Jon Skeet's answer to Is it correct to use JavaScript Array.sort() method for shuffling?.

like image 54
Andy E Avatar answered Oct 19 '22 03:10

Andy E


If "truly" randomness is important, I recommend against this. See my below edit.

I just wanted to add my favorite method for a little variety ;)

Given a string:

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

Shuffle in one line:

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

Outputs:

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

EDIT: As @PleaseStand has pointed out, this doesn't meet OP's question at all since it does suffer from "Microsoft's Browser Choice shuffle" code. This isn't a very good randomizer if your string needs to be close to random. It is however, awesome at quickly "jumbling" your strings, where "true" randomness is irrelevant.

The article he links below is a great read, but explains a completely different use case, which affects statistical data. I personally can't imagine a practical issue with using this "random" function on a string but as a coder, you're responsible for knowing when not to use this.

I've left this here for all the casual randomizers out there.

like image 38
Joel Mellon Avatar answered Oct 19 '22 02:10

Joel Mellon


Shortest One Liner:

const shuffle = str => [...str].sort(()=>Math.random()-.5).join('');

Does not guarantee statistically equal distribution but usable in most cases for me.

const shuffle = str => [...str].sort(()=>Math.random()-.5).join('');
document.write(shuffle("The quick brown fox jumps over the lazy dog"));
like image 12
chickens Avatar answered Oct 19 '22 02:10

chickens