-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathstructy-099-substitutingSynonyms.js
101 lines (87 loc) · 2.75 KB
/
structy-099-substitutingSynonyms.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
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
// p: str, obj
// r: arr
// const sentence = "follow the yellow brick road";
// const synonyms = {
// follow: ["chase", "pursue"],
// yellow: ["gold", "amber", "lemon"],
// };
// substituteSynonyms(sentence, synonyms);
// [
// 'chase the gold brick road',
// 'chase the amber brick road',
// 'chase the lemon brick road',
// 'pursue the gold brick road',
// 'pursue the amber brick road',
// 'pursue the lemon brick road'
// ]
// f t y b r ['']
// c / p \
// t y b r [c] [p]
// t| t|
// y b r [ct] [pt]
// g/ a/ l\ g/ a/ l\
// b r [ctg] [cta] [ctl] [ptg] [pta] [ptl]
// b| b| b| b| b| b|
// [ctgb] [ctab] [ctlb] [ptgb] [ptab] [ptlb]
// const sentence = "follow the yellow brick road";
// const synonyms = {
// follow: ["chase", "pursue"],
// yellow: ["gold", "amber", "lemon"],
// };
// recursive
const substituteSynonyms = (sentence, synonyms) => {
if (sentence === "") return [""];
let result = [];
const iOfSpace = sentence.indexOf(" ");
let firstW = iOfSpace > 0 ? sentence.slice(0, iOfSpace) : sentence;
let restS = iOfSpace > 0 ? sentence.slice(iOfSpace + 1) : "";
// console.log(iOfSpace, firstW);
let restSentence = substituteSynonyms(restS, synonyms);
if (firstW in synonyms) {
for (let r of restSentence) {
for (let s of synonyms[firstW]) {
result.push(s + " " + r);
}
}
} else {
for (let r of restSentence) {
result.push(firstW + " " + r);
}
}
return result.map((r) => r.trim());
};
// // iterative O(n^m) O(n^m)
// const substituteSynonyms = (sentence, synonyms) => {
// let result = [[]];
// let array = sentence.split(" ");
// for (let a of array) {
// if (a in synonyms) {
// let clone = [];
// for (let r of result) {
// for (let s of synonyms[a]) {
// clone.push([...r, s]);
// }
// }
// result = [...clone];
// } else {
// for (let r of result) {
// r.push(a);
// }
// }
// }
// return result.map((r) => r.join(" "));
// };
const sentence = "follow the yellow brick road";
const synonyms = {
follow: ["chase", "pursue"],
yellow: ["gold", "amber", "lemon"],
};
console.log(substituteSynonyms(sentence, synonyms));
// [
// 'chase the gold brick road',
// 'chase the amber brick road',
// 'chase the lemon brick road',
// 'pursue the gold brick road',
// 'pursue the amber brick road',
// 'pursue the lemon brick road'
// ]