0

I've been wrapping my head around this for a while, the solution needs to be written in JS.

I need to make every possible sentence based on an array of options for each word, will explain in detail below:

Hello | my | name | is | John 

Is the main sentence I will base this example off, each word in the sentence has a dynamic array of other words that could take their space.

let firstWord = ["Hello", "Hi", "Howdy"];
let secondWord = ["my", "your"];
let thirdWord = ["name"];
let fourthWord = ["is", "isn't"];
let fifthWord = ["John"];

I tried to find out the number of possible sentences by multiplying each array length, then iterating through the arrays to fill it out but can not grasp the iteration method I need to do this.

How could I solve this?

  • This is called a cartesian product. Write a loop for each word position -- first is outer, fifth is innermost, and in the inside of all the loops, that's one result. – ggorlen Aug 27 '21 at 01:36
  • Oh awesome, thanks will check this out! – Tomas Brown Aug 27 '21 at 01:37
  • Here's a trivial example if the arrays are fixed: `[1,2,3].flatMap(x => [4,5,6].flatMap(y => [7,8,9].map(z => [x, y, z])))`. Replace the arrays with your arrays and add more layers of loops. If you don't know how many words, use the link answers. – ggorlen Aug 27 '21 at 01:40
  • Arrays are all very dynamic, with any number of words in a sentence and any number of options for each word. – Tomas Brown Aug 27 '21 at 02:21

0 Answers0