Reputation: 11448
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?
Upvotes: 1
Views: 1270
Reputation: 150080
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/
Upvotes: 1