0

I have a string listing words/tokens like this:

input = "im ac ad af al ap ar de died cat",

how to generate randomized "words" output based on that, e.g.

output = "ac im al ad af ap ar cat de died",
Eddie
  • 26,593
  • 6
  • 36
  • 58
Tom
  • 6,725
  • 24
  • 95
  • 159

2 Answers2

2

A simple solution using array.sort()..
It is simpler than what is proposed in the duplicate link... but it does the work

const input = "im ac ad af al ap ar de died cat";

console.log(input.split(' ').sort(() => Math.floor(Math.random() * Math.floor(3)) - 1).join(' '))
ben
  • 3,558
  • 1
  • 15
  • 28
0

you can loop through the array few times to shuffle.

input = "im ac ad af al ap ar de died cat";
input = input.split(' ');

for (var i = 0; i < input.length; i++){
 let ind1 = Math.floor(Math.random() * (input.length));
 let ind2 = Math.floor(Math.random() * (input.length));
 [input[ind1], input[ind2]] =  [input[ind2], input[ind1]];
}

console.log(input.join(' '));
atiq1589
  • 2,227
  • 1
  • 16
  • 24