2

I want to make random words with letters provided via array with Javascript.
For example, I have a literal array that contains three letters:

var letters = ["a", "b", "c"];

I want to make random words by specifying "return 3 letters", for example:

abc
cba
bac
bba
ccb

I made a code that does something like this, but only returns 1 letter. I was wondering if there was a way to return a certain amount of letters?

Here is what I have (very simple):

var letters = ["a", "b", "c"];
var word = letters[Math.floor(Math.random() * letters.length)];

I know I can make an array, and fill it with "abc", "cba", etc. but I need it to make words with array values that are provided.

Matthew
  • 2,158
  • 7
  • 30
  • 52

2 Answers2

1

try this:

var letters = ["a", "b", "c"];
var wordlength = 3;
var word = "";
for(var i = 0; i < wordlength; i++){
word += letters[Math.floor(Math.random() * letters.length)];
}
alert(word);
localhost
  • 89
  • 3
0

It is one type of permutation problem you can find many online solutions for this. And there is an algorithm implemented in java script you can directly use that.

see the below linked questions on stack overflow.

Permutation of array

Permutations in JavaScript?

Community
  • 1
  • 1
smali
  • 4,687
  • 7
  • 38
  • 60