Anjanesh Lekshminarayanan
Anjanesh

Anjanesh

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;

do
{    
    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

    randomIndices.push(indexValue);

} while (arrayIndices.length > 0)

let random_phrase = "";

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

console.log(random_phrase);

node jumble.js

 
Share this