mercredi 6 mai 2015

Randomly space characters throughout string?

To shuffle a string, I could use something like this

String.prototype.shuffle = function () {
    var arr = this.split("");
    var len = arr.length;
    for (var n = len - 1; n > 0; n--) {
        m = Math.floor(Math.random() * (n + 1));
        tmp = arr[n];
        arr[n] = arr[m];
        arr[m] = tmp;
    }
    return arr.join("");
}

But how could I randomly space it with n characters, while preserving the string order?

For example:

"test"   =>   "t-es--t"
"test"   =>   "-t-e-st"
"test"   =>   "te--st-"

I've thought about creating a list from the string, generating a random number to represent an index, and then shifting the list to the left, but is there a better way to do this?

Aucun commentaire :

Enregistrer un commentaire