One way to do it is to loop through the characters of a string (now in an array) one by one. For each character, swap it with a random character that appears earlier in the array. This way we can guarantee that we preserve the number of specific characters in the array.
In the above program we have a function called scramble that takes a string (word) as input. The first line of scramble converts the string into an array (strarray). This conversion is done using the split() method. Similarly the last two lines of the function convert the array back to a string and return it. Likewise, this conversion is done using the join() method.
Within the function we loop through the array. For each element we find a random location preceding that element’s location. Then we swap the characters using these three lines:
If we run this program, we will obtain:
(your specific output might vary due to the random choice of characters to swap.)
To understand more about how this program, let us write some document.write() statements, like so:
The output is (for instance):
As the output above shows, for the first character (namely, ‘k’) there is no other character to swap it with, so it is swapped with itself giving the same string, i.e., ‘kodeclik’. The second character (‘o’) is swapped with the first (‘k’), yielding ‘okdeclik’. This process continues till the last character, which is ‘k’. This is swapped with ‘d’ yielding ‘kilckoed’ as the final string which is returned and printed by the program.
Kodeclik is an online coding academy for kids and teens to learn real world programming. Kids are introduced to coding in a fun and exciting way and are challeged to higher levels with engaging, high quality content.