Jumbling a string randomly

There was a situation where a string had to be randomly jumbled. If we get all possible permutations of the string and pick one random one it'll work. But all possible permutations of the string can take a long time to generate if the string is long as the number of permutations is the factorial of the length of the string. So, for a 10 letter string there are 3,628,800 permutations.

There is an easier method. This just picks a random index of the indices of the string and stores the indices in another array which is then used to 'stitch' to get the jumbled string.

const phrase = "elephant";

let arrayIndices = [ ...Array(phrase.length).keys() ]; 
// [0,1,2,3,4,5,6,7] = the values of this array is the indices of the string elephant

let randomIndices = [];
let indexValue, r = undefined;

    r = Math.floor((Math.random() * arrayIndices.length));
    // r is a random index between 0 and the length of the arrayIndices array. 0-7 on first run, 0-6 on second run, 0-5 on third run etc

    indexValue = arrayIndices.splice(r, 1)[0];
    // Delete index r and return the value of it which is also an index - random index in the string elephant


} while (arrayIndices.length > 0)

let random_phrase = "";

for (let i = 0; i < phrase.length; i++)
    random_phrase += phrase[randomIndices[i]];


node jumble.js

Did you find this article valuable?

Support Anjanesh Lekshminarayanan by becoming a sponsor. Any amount is appreciated!