function shuffleString(text, key) {
const array = text.split('');
let seed = key;
const random = () => {
const x = Math.sin(seed++) * 10000;
return x - Math.floor(x);
};
for (let i = array.length - 1; i > 0; i--) {
const j = Math.floor(random() * (i + 1));
[array[i], array[j]] = [array[j], array[i]];
}
return array.join('');
}
// Example usage:
const text = '123456';
const key = 20;
const shuffledText = shuffleString(text, key);
console.log(shuffledText); // Output: '231465'
const shuffledTextAgain = shuffleString(text, key);
console.log(shuffledTextAgain); // Output: '231465'
The shuffleString
function takes two parameters: text
, which is the input string to be shuffled, and key
, which is a numeric value used to determine the shuffling order.
The function uses the Fisher-Yates algorithm to shuffle the characters in the text
string. The shuffling is based on a custom pseudo-random number generator that is seeded with the provided key
value.
Here's a step-by-step explanation of how the shuffleString
function works:
- The input
text
is split into an array of individual characters. - The
key
value is used to initialize a seed for the pseudo-random number generator. - The
random
function is defined within theshuffleString
function. It generates pseudo-random values between 0 and 1 using a custom implementation based on the sine function and the incrementedseed
value. - The Fisher-Yates algorithm is used to iterate over the array of characters from the last element to the first.
- For each iteration, a random index
j
is generated using therandom
function. The indexj
is a random integer between 0 and the current indexi
. - The character at index
i
and the character at indexj
are swapped using destructuring assignment:[array[i], array[j]] = [array[j], array[i]]
. - After all iterations are complete, the shuffled array of characters is joined back into a string.
- The shuffled string is returned as the output of the
shuffleString
function.
By providing a specific key
value, you can consistently reproduce the same shuffling order for the same input text
. The shuffled output will be different for different key
values.
I hope this clarifies how the shuffleString
function works. Let me know if you have any further questions!
Top comments (0)