1

I have a small string and a fixed seed and I am trying to shuffle all the string elements with the given seed so its repeatable.

Here is the code I have:

function shufff(strin,seed){
    var tem;
    var j;
    var tt = strin.length;
    for(var i=0; i<tt; i++){
        j = ( seed % (i+1) + i) % tt;
        tem=strin[i];
        strin[i] = strin[j];
        strin[j] = tem;
    }
    return strin;
}

var tom='tomollow';
alert(shufff(tom,6543));

This returns the original string back with no shuffling.

What am I doing wrong?

David19801
  • 11,214
  • 25
  • 84
  • 127
  • Strings are immutable, and this is a poor shuffling strategy even after fixing the assignment. See [Predictable Javascript array shuffle](https://stackoverflow.com/questions/28256506/predictable-javascript-array-shuffle), [Javascript random ordering with seed](https://stackoverflow.com/questions/16801687/javascript-random-ordering-with-seed) and [How do I replace a character at a particular index in JavaScript?](https://stackoverflow.com/questions/1431094/how-do-i-replace-a-character-at-a-particular-index-in-javascript) – ggorlen Jul 25 '21 at 22:40

1 Answers1

1

Array-style access to individual characters in JavaScript strings is read only. (And not supported at all in older browsers.)

A minimal change to your code to get it to work would be to convert your string to an array for processing and then convert it back to a string when you return it:

function shufff(strin,seed){
    strin = strin.split("");
    var tem;
    var j;
    var tt = strin.length;
    for(var i=0; i<tt; i++){
        j = ( seed % (i+1) + i) % tt;
        tem=strin[i];
        strin[i] = strin[j];
        strin[j] = tem;
    }
    return strin.join("");
}

Working demo: http://jsfiddle.net/fcKDN/

nnnnnn
  • 147,572
  • 30
  • 200
  • 241
  • +1, you beat me to the post with both the answer and the revised code *and* included the demo :-) – Andy E Jan 27 '12 at 09:53
  • Thanks @AndyE - funny how similar our answers ended up, even to the point that we both re-used the `strin` variable/argument instead of creating a new variable for the working array (a practice that some of my colleagues frown on, but obviously I prefer it as long as it seems clear in any given case). – nnnnnn Jan 27 '12 at 10:06
  • yeah, I thought the same. The only difference was where we put it :-). It's a practice I don't use often, I must say. If I'd written the whole thing myself, I'd have done a few things different (like a single `var` statement, additional variable, etc), but reusing the `strin` variable meant less modification of the OPs code, so... just put it down to laziness on my part ;-) – Andy E Jan 27 '12 at 10:14