Last active
October 29, 2016 18:20
-
-
Save rijvirajib/0d66df37a119bff078c9a04774396d45 to your computer and use it in GitHub Desktop.
Find the smallest set of words
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
const text = 'the dog is very large and very slow but it is my dog'.split(' '); | |
let smallest = []; | |
let smallest_array = []; | |
let query = { | |
dog: -1, | |
very: -1, | |
slow: -1 | |
} | |
let words_not_found = Object.keys(query); | |
let checkSmallest = (query) => { | |
let array_of_query = Object.keys(query).map(function(v) { return query[v]; }); | |
if (getRange(smallest) > getRange(array_of_query)) { | |
smallest_array.length = 0; | |
smallest = array_of_query; | |
smallest_array.push(smallest); | |
} else if (getRange(smallest) === getRange(array_of_query)) { | |
smallest_array.push(array_of_query) | |
} | |
} | |
let getRange = (indices) => { | |
let max = Math.max.apply(null, indices) | |
let min = Math.min.apply(null, indices) | |
return Math.abs(max - min); | |
} | |
text.forEach( (word, index) => { | |
if (query[word] !== undefined) { | |
query[word] = index; | |
if (words_not_found.length > 0) { | |
let word_found = words_not_found.indexOf(word); | |
if ( word_found > -1 ) { | |
words_not_found.splice(word_found, 1); | |
} | |
} else { | |
checkSmallest(query); | |
} | |
} | |
}); | |
console.log(smallest); | |
console.log(smallest_array); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment