Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // Implement an autocomplete system. That is, given a "query" string and
- // a set of all possible query strings, return all strings in the set that
- // have "query" as prefix
- // For example, if query = "de" and the set of string is [dog, deer, deal]
- // , I have to return the list [deer, deal]
- function autocomplete(query, allStrings){
- // First, I will create a list with all the strings that have equal or bigger length than my query
- let n = query.length;
- let possibleStrings = [];
- for(let i=0; i<allStrings.length; i++){
- let message = allStrings[i];
- if(message.length >= n){
- possibleStrings.push(message);
- }
- }
- // Secondly, I check the strings in my list that have my query as prefix
- let suggestedStrings = [];
- for(let i=0; i<possibleStrings.length; i++){
- let message = possibleStrings[i];
- // Now, I have to check if my "query" is prefix of "message"
- let hits = 0;
- for(let j=0; j<n; j++){
- if(message[j] === query[j]){
- hits++;
- }
- }
- // "Query" is prefix of message, when I have n hits (like the length of my "query")
- if(hits === n){
- suggestedStrings.push(message);
- }
- }
- return suggestedStrings;
- }
- // MAIN FUNCTION
- let allStrings = ["complete", "compare", "construct", "campaign", "detroit", "disturb", "destroy", "demonstrate"];
- console.log();
- console.log("***********************************************************************************************");
- console.log("***********************************************************************************************");
- console.log();
- console.log("allStrings = " + allStrings);
- console.log();
- let queries = ["c", "co", "com", "compare", "d", "de" , "e", "fffffffffff"];
- for(let i=0; i<queries.length; i++){
- let query = queries[i];
- let suggestedStrings = autocomplete(query, allStrings);
- console.log("Query = " + query + " ----> " + suggestedStrings);
- console.log();
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement