tox
tox

Reputation: 49

Math.random() and variable

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

Upvotes: 0

Views: 3537

Answers (2)

Thomas Li
Thomas Li

Reputation: 3338

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

Upvotes: 1

Naftali
Naftali

Reputation: 146360

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)

Upvotes: 1

Related Questions