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.

3
  • You could just call letters[Math.floor(Math.random() * letters.length)] three times and concatenate the letters. Commented Jul 15, 2014 at 5:49
  • @Felix Kiling.Is random() guarantees that it will return different value Commented Jul 15, 2014 at 5:51
  • 1
    No, but you will get a random value in the range of [0,1) every time you call the function. Commented Jul 15, 2014 at 5:52

2 Answers 2

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);
Sign up to request clarification or add additional context in comments.

Comments

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?

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.