Last active
August 24, 2021 19:47
-
-
Save Gerst20051/aa9dc2044840cd223c762b29f30a8a8f to your computer and use it in GitHub Desktop.
Word Split
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
function WordSplit(strArr) { | |
const word = strArr[0]; | |
const substrings = generateSubstrings(word); | |
const words = substrings.filter(substring => strArr[1].includes(substring)); | |
const pairs = generatePairs(words); | |
const pair = pairs.find(pair => pair.join('') === word); | |
return pair ? pair.join(',') : 'no pair'; | |
} | |
function generateSubstrings(str) { | |
const substrings = []; | |
for (let i = 0; i < str.length; i++) { | |
for (let j = i + 1; j < str.length + 1; j++) { | |
substrings.push(str.slice(i, j)); | |
} | |
} | |
return substrings; | |
} | |
function generatePairs(arr) { | |
const pairs = []; | |
for (let i = 0; i < arr.length; i++) { | |
for (let j = i; j < arr.length - 1; j++) { | |
pairs.push([arr[i], arr[j + 1]]); | |
} | |
} | |
return pairs; | |
} | |
console.log(WordSplit([ 'baseball', 'a,all,b,ball,bas,base,cat,code,d,e,quit,z' ])); // base,ball | |
console.log(WordSplit([ 'abcgefd', 'a,ab,abc,abcg,b,c,dog,e,efd,zzzz' ])); // abcg,efd |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Sure I'll look into doing that at some point!