-
-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathindex.js
42 lines (32 loc) · 1.29 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
'use strict';
/**
* Function `generateSentences` takes 2D array of words as input
* Returns array of all the sentences possible to form using the words
* It keeps the order of words same in sentence as given in input
* First row will be first word in the sentence, second row will be second and so on
* It will generate sentences equals to the number of rows in the 2D array
*/
const generateSentences = (wordsList) => {
if (wordsList === null || wordsList.length === 0) {
return null;
}
// To hold the temporary data
const sentences = Array(wordsList.length).fill('');
// Array to hold all the sentences formed.
const generatedSentences = [];
for (let i = 0; i < wordsList[0].length; i++) {
generateSentencePermutations(wordsList, 0, i, sentences, generatedSentences);
}
return generatedSentences;
};
const generateSentencePermutations = (wordsList, startIndex, wordIndex, sentences, generateSentences) => {
sentences[startIndex] = wordsList[startIndex][wordIndex];
if (startIndex === (wordsList.length - 1)) {
generateSentences.push(sentences.join(' '));
return;
}
for (let i = 0; i < wordsList[startIndex + 1].length; i++) {
generateSentencePermutations(wordsList, startIndex + 1, i, sentences, generateSentences);
}
};
module.exports = generateSentences;