0

how can i randomize for this variable one word?

var = 'stack';

for (i=0; i<5; i++){
   document.write( Math.random() ??? + '<br />');
}

sample result:

t
c
k
a
s

thanks

Naftali
  • 144,921
  • 39
  • 244
  • 303
tox
  • 49
  • 1
  • 7
  • http://stackoverflow.com/questions/3943772/how-do-i-shuffle-the-characters-in-a-string-in-javascript ? – stecb May 16 '11 at 16:09

2 Answers2

1

Here is a solution:

var st = 'stack';

for (i=0; i<st.length; i++){
    var random = (Math.random() * st.length);
    document.write( st.slice(random, random+1) + '<br />');
}

Fiddle: http://jsfiddle.net/maniator/Xx4NA/ (keep pressing Run to see it run differently every time)

Naftali
  • 144,921
  • 39
  • 244
  • 303
  • @Neal -- when I ran your fiddle I got the following: c k s a c – El Guapo May 16 '11 at 16:13
  • @ElGuapo, it is random, every `run` will have a different result – Naftali May 16 '11 at 16:13
  • Right on.. yeah.. guess that makes sense... I thought @tox wanted each letter to show up, but randomized. Probably a bad assumption. – El Guapo May 16 '11 at 16:14
  • Is it suppose to be using individual chars more than once? Or is it suppose to merely shuffle the order of the chars? – Sampson May 16 '11 at 16:15
  • @Jonathan, i am not the OP, i just went with what it looked like the answer was to the query – Naftali May 16 '11 at 16:16
  • @Neal I was only asking since the OP's example appear to be a shuffling of the letters alone. – Sampson May 16 '11 at 16:21
  • @Jonathan, i understand your question. i think we are all a bit thrown by the OP's example, but the OP said that that was a `sample result` which can mean there could be more results – Naftali May 16 '11 at 16:22
  • @tox, pick one tho lol, stop goin back and forth, its making me dizzy – Naftali May 16 '11 at 16:51
1

Revised as Neal pointed out that the previous solution does not take into account of duplicated letters:

var randomIndexes = new Array();
for (i = 0; i < word.length; i++) {
    randomIndexes[i] = -1;
}

for (i = 0; i < word.length; i++) {
    while (randomIndexes[i] == -1) {
        randomIndexes[i] = Math.floor(Math.random() * word.length);
        for (j = 0; j < i; j++) {
            if (randomIndexes[i] == randomIndexes[j]) {
                randomIndexes[i] = -1;
                break;
            }
        }
    }
}

for (i = 0; i < word.length; i++) {
    document.write(word.charAt(randomIndexes[i]));
}
Thomas Li
  • 3,358
  • 18
  • 14