Yahoo Answers is shutting down on May 4th, 2021 (Eastern Time) and beginning April 20th, 2021 (Eastern Time) the Yahoo Answers website will be in read-only mode. There will be no changes to other Yahoo properties or services, or your Yahoo account. You can find more information about the Yahoo Answers shutdown and how to download your data on this help page.

Mt srting is not shuffled WHY?

String.prototype.shuffle = function(){

var tmp,cur,top = this.length;

if(top) while(--top){

cur = Math.floor(Math.random() * (top + 1));

tmp = this[cur];

this[cur] = this[top];

this[top] = tmp;

}

return this;

}

randomWord = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklm...

console.log(randomWord.substr(0,8));

//output

ABCDEFGH

why it is not shuffled

2 Answers

Relevance
  • Leo D
    Lv 6
    8 years ago
    Favorite Answer

    I'm not an expert on JavaScript honestly, but the primary reason why I believe this is happening is because I believe that strings are immutable.

    Now that last part of the second to last line got caught off because of Yahoo Answer's cut off point, but I imagine that you used .shuffle() at the end of the two alphabet string literal. If you didn't, you have to remember to do this. The immutability of strings means that you can't actually shuffle the string but you have to instead shuffle a copy and return it.

    About the copy, the copy can't be another string, which I believe is what you did. You need to create a character array. You can do that by doing some thing like this { var carr = this.split(""); }. This will split the String into a character array split after every character. (toCharArray should probably be its own function, but I don't know how worth it this added modularity would be in JS.) Operate on the character array { carr } instead of { this }.

    Once you have finished, return carr.join("") instead of { this }. That's it :)

    Remember that if { text } is your string, calling { shuffle() } on it won't shuffle the string, but return a shuffled copy of the string. The way you could get around that is by creating a mutable string container (like a string buffer), but again that might not be worth it.

  • 8 years ago

    You can't modify a single character in a string:

    this[cur] = this[top];

    this[top] = tmp;

    But you can turn the string into an array and then modify the bits in the array, and then join them.

    Try this: http://pastebin.com/EFkBbQUc

Still have questions? Get your answers by asking now.