-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathallConstruct.js
More file actions
24 lines (21 loc) · 998 Bytes
/
allConstruct.js
File metadata and controls
24 lines (21 loc) · 998 Bytes
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
const allConstruct = (targetWord, wordBank, cache = {}) => {
if (targetWord in cache) return cache[targetWord]
//checking current target
if (targetWord === "") return [[]];
//iterating over wordbank for all word combinations
let allPossible = []
for (let word of wordBank) {
//checking whether target word starts with current word
if (targetWord.startsWith(word)) {
let suffixWays = allConstruct(targetWord.slice(word.length), wordBank, cache)
const targetWays = suffixWays.map(way => [word,...way])
allPossible.push(...targetWays)
}
}
cache[targetWord] = allPossible
return allPossible
}
console.log(allConstruct('purple', ['pu', 'p', 'le', 'ur', 'rple']))
console.log(allConstruct('saiteja', ['sa', 'ja', 'teja', 'si', 'eja', 'i']))
console.log(allConstruct('eeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeeef', ['e', 'eee',
'eeeeeeeeee', 'eeeeeeeee', 'eeeeeee', 'eeeeeeeeeeeeeeeeeeeeeeeeeee']))