Skip to content

Instantly share code, notes, and snippets.

@tonis2
Last active September 29, 2018 08:48
Show Gist options
  • Save tonis2/43d8003a9237adbb4adad68d46202240 to your computer and use it in GitHub Desktop.
Save tonis2/43d8003a9237adbb4adad68d46202240 to your computer and use it in GitHub Desktop.
Regex exercise interview question
/*
write a function that takes two inputs:
 vocabulary - array of strings (words)
 sentence - string
and returns:
 true - if the sentence can be split in the words given; words can be repeated, words can have any order; you can use only subset of words
 false - if the sentence cannot be split in the words
Both sentence and words contain only lower-letter characters [a-z].
Note: the sentence does not need to be semantically correct.
example:
words = [“i”, “am”, “here”]
sentence: 
  “iamhere” -> true
  “amami” -> true
  “iambla” -> false
*/
const vocabulary = ["i", "am", "here"];
const sentence = "iamhere";
const sentence2 = "amami";
const sentence3 = "iambla";
const solve_riddle = (vocabulary, sentence) => {
const regex = new RegExp(`(${vocabulary.join("|")})`, "g");
const test = sentence.match(regex).join("");
return test.length == sentence.length;
};
const result1 = solve_riddle(vocabulary, sentence);
const result2 = solve_riddle(vocabulary, sentence2);
const result3 = solve_riddle(vocabulary, sentence3);
console.log(result1, result2, result3);
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment