简体   繁体   中英

I tried using a fisher-yates shuffle for strings, but it didn't work

I tried shuffling a string with a fisher-yates shuffle, but although it properly gets the indexes and the values, it doesn't shuffle the string, what is wrong?

 globalVar = 'I am GLOBAL' function scrambler(anyString) { let placeHolder = anyString for (let i = placeHolder.length - 1; i >= 0; i--) { let swapIndex = Math.floor(Math.random() * (i + 1)) let chartoSwap = placeHolder[swapIndex] let currentChar = placeHolder[i] placeHolder[i] = chartoSwap placeHolder[swapIndex] = currentChar } return placeHolder } let scrambled = scrambler(globalVar) console.log(scrambled)

strings are immutable. Change placeHolder into an array

 globalVar = 'I am GLOBAL' function scrambler(anyString) { let placeHolder = anyString.split("") for (let i = placeHolder.length - 1; i >= 0; i--) { let swapIndex = Math.floor(Math.random() * (i + 1)) let chartoSwap = placeHolder[swapIndex] let currentChar = placeHolder[i] placeHolder[i] = chartoSwap placeHolder[swapIndex] = currentChar } return placeHolder.join("") } let scrambled = scrambler(globalVar) console.log(scrambled)

Strings are immutable and you cannot mutate them. Read this for more information: https://stackoverflow.com/a/1431113/1128441

String.prototype.replaceAt=function(index, replacement) {
  return this.substr(0, index) + replacement+ this.substr(index + replacement.length);
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM