Skip to content
Advertisement

generate one of the mutiple possibles anagrams of a string

I’m kind of new to JavaSCript and I want to ask wow can I make a random anagram generator, without a list of all possible anagrams (because that’s not optimized)

Example:

input: “abc”

output: get the input, split it ([“a”, “b”, “c”]), randomize the split and join them ([“cba”])

This is for a command for my bot in Discord.

I’ve searched about this, but I just found generators for all anagrams possible in the same string.

Thank you for reading this, have a nice day

Advertisement

Answer

Well, you’ve explained it yourself. You just had to search for the commands online…

const input = 'abc';
const output = input
  .split('') // make it into strings
  .sort(() => 0.5 - Math.random()) // shuffle
  .join(''); // convert to a string

Not sure if you need the result to be an array of a single item, or just a string 😐

Also, keep in mind the output might be the same as the input! If you don’t want this – call the function as many times as needed in order to get a different output.


Edit: as @PA mentioned, using the above-mentioned way to sort arrays is not a great idea. Even though it might currently work, it can lead to bad results. The reason is that the sort algorithm might (not sure) need static values for each item. Theoretically, that might be a problem. Therefore something like this can be used:

const input = 'abc';
const output = input
  .split('') // make it into strings
  .map((v) => [Math.random(), v]) // convert the array of characters into tuples (pairs)
  // of a random element and the real value
  .sort((a, b) => a[0] - b[0]) // sort, based on the random values
  .map(([rand, value]) => value) // return to list of characters
  .join(''); // convert to a single string

This way you set the random value once, then do the shuffling, then remove the random values.

User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement