jeudi 26 février 2015

randomly splice values into array

I have an array "A" of scrambled, randomly generated ASCII characters... and a message "M". I want to insert the characters of message M into array A such that the order of M's characters are intact... but randomly distributed throughout array A.


Original array: zH$@%@$#@$@^^#@(%*$@^&@!$^%&


Sample output: zH$@%@^t$#@$@^^h#@(%*$@^&@i!$^%&s, etc...



var randomChars = [];
for(var i=33;i<127;++i) {
var letter = document.createElement('span');
letter.innerHTML = String.fromCharCode(i);
randomChars.push(letter);
}

var message = "this is a message";
for (var i = 0; i < message.split("").length; i++) {
var rand = Math.floor((Math.random() * randomChars.length) + 1);
var letters = document.createElement('span');
letters.innerHTML = message.split("")[i];
letters.setAttribute("hidden","");
randomChars.splice(rand, 0, letters);
}


Fiddle: http://ift.tt/1DelYzN





Aucun commentaire:

Enregistrer un commentaire