Advertisement
makispaiktis

DCP11 - Implement an autocomplete system

Sep 5th, 2020 (edited)
398
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
  1. // Implement an autocomplete system. That is, given a "query" string and
  2. // a set of all possible query strings, return all strings in the set that
  3. // have "query" as prefix
  4. // For example, if query = "de" and the set of string is [dog, deer, deal]
  5. // , I have to return the list [deer, deal]
  6.  
  7. function autocomplete(query, allStrings){
  8.     // First, I will create a list with all the strings that have equal or bigger length than my query
  9.     let n = query.length;
  10.     let possibleStrings = [];
  11.     for(let i=0; i<allStrings.length; i++){
  12.         let message = allStrings[i];
  13.         if(message.length >= n){
  14.             possibleStrings.push(message);
  15.         }
  16.     }
  17.     // Secondly, I check the strings in my list that have my query as prefix
  18.     let suggestedStrings = [];
  19.     for(let i=0; i<possibleStrings.length; i++){
  20.         let message = possibleStrings[i];
  21.         // Now, I have to check if my "query" is prefix of "message"
  22.         let hits = 0;
  23.         for(let j=0; j<n; j++){
  24.             if(message[j] === query[j]){
  25.                 hits++;
  26.             }
  27.         }
  28.         // "Query" is prefix of message, when I have n hits (like the length of my "query")
  29.         if(hits === n){
  30.             suggestedStrings.push(message);
  31.         }
  32.     }
  33.     return suggestedStrings;
  34. }
  35.  
  36. // MAIN FUNCTION
  37. let allStrings = ["complete", "compare", "construct", "campaign", "detroit", "disturb", "destroy", "demonstrate"];
  38. console.log();
  39. console.log("***********************************************************************************************");
  40. console.log("***********************************************************************************************");
  41. console.log();
  42. console.log("allStrings = " + allStrings);
  43. console.log();
  44. let queries = ["c", "co", "com", "compare", "d", "de" , "e", "fffffffffff"];
  45. for(let i=0; i<queries.length; i++){
  46.     let query = queries[i];
  47.     let suggestedStrings = autocomplete(query, allStrings);
  48.     console.log("Query = " + query + " ----> " + suggestedStrings);
  49.     console.log();
  50. }
  51.  
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement