├── .gitignore ├── LICENSE ├── README.md ├── TrieDictionary ├── Program.cs ├── Trie.cs ├── TrieDictionary.csproj ├── TrieDictionary.sln └── TrieDictionaryTest │ ├── GlobalUsings.cs │ ├── TrieDictionaryTest.csproj │ └── TrieTest.cs └── TrieDictionarySolution ├── Program.cs ├── Trie.cs ├── TrieDictionarySolution.csproj ├── TrieDictionarySolution.sln └── TrieDictionaryTest ├── GlobalUsings.cs ├── TrieDictionaryTest.csproj └── TrieTest.cs /.gitignore: -------------------------------------------------------------------------------- 1 | ## Ignore Visual Studio temporary files, build results, and 2 | ## files generated by popular Visual Studio add-ons. 3 | ## 4 | ## Get latest from https://github.com/github/gitignore/blob/main/VisualStudio.gitignore 5 | 6 | # User-specific files 7 | *.rsuser 8 | *.suo 9 | *.user 10 | *.userosscache 11 | *.sln.docstates 12 | 13 | # User-specific files (MonoDevelop/Xamarin Studio) 14 | *.userprefs 15 | 16 | # Mono auto generated files 17 | mono_crash.* 18 | 19 | # Build results 20 | [Dd]ebug/ 21 | [Dd]ebugPublic/ 22 | [Rr]elease/ 23 | [Rr]eleases/ 24 | x64/ 25 | x86/ 26 | [Ww][Ii][Nn]32/ 27 | [Aa][Rr][Mm]/ 28 | [Aa][Rr][Mm]64/ 29 | bld/ 30 | [Bb]in/ 31 | [Oo]bj/ 32 | [Ll]og/ 33 | [Ll]ogs/ 34 | 35 | # Visual Studio 2015/2017 cache/options directory 36 | .vs/ 37 | # Uncomment if you have tasks that create the project's static files in wwwroot 38 | #wwwroot/ 39 | 40 | # Visual Studio 2017 auto generated files 41 | Generated\ Files/ 42 | 43 | # MSTest test Results 44 | [Tt]est[Rr]esult*/ 45 | [Bb]uild[Ll]og.* 46 | 47 | # NUnit 48 | *.VisualState.xml 49 | TestResult.xml 50 | nunit-*.xml 51 | 52 | # Build Results of an ATL Project 53 | [Dd]ebugPS/ 54 | [Rr]eleasePS/ 55 | dlldata.c 56 | 57 | # Benchmark Results 58 | BenchmarkDotNet.Artifacts/ 59 | 60 | # .NET Core 61 | project.lock.json 62 | project.fragment.lock.json 63 | artifacts/ 64 | 65 | # ASP.NET Scaffolding 66 | ScaffoldingReadMe.txt 67 | 68 | # StyleCop 69 | StyleCopReport.xml 70 | 71 | # Files built by Visual Studio 72 | *_i.c 73 | *_p.c 74 | *_h.h 75 | *.ilk 76 | *.meta 77 | *.obj 78 | *.iobj 79 | *.pch 80 | *.pdb 81 | *.ipdb 82 | *.pgc 83 | *.pgd 84 | *.rsp 85 | *.sbr 86 | *.tlb 87 | *.tli 88 | *.tlh 89 | *.tmp 90 | *.tmp_proj 91 | *_wpftmp.csproj 92 | *.log 93 | *.tlog 94 | *.vspscc 95 | *.vssscc 96 | .builds 97 | *.pidb 98 | *.svclog 99 | *.scc 100 | 101 | # Chutzpah Test files 102 | _Chutzpah* 103 | 104 | # Visual C++ cache files 105 | ipch/ 106 | *.aps 107 | *.ncb 108 | *.opendb 109 | *.opensdf 110 | *.sdf 111 | *.cachefile 112 | *.VC.db 113 | *.VC.VC.opendb 114 | 115 | # Visual Studio profiler 116 | *.psess 117 | *.vsp 118 | *.vspx 119 | *.sap 120 | 121 | # Visual Studio Trace Files 122 | *.e2e 123 | 124 | # TFS 2012 Local Workspace 125 | $tf/ 126 | 127 | # Guidance Automation Toolkit 128 | *.gpState 129 | 130 | # ReSharper is a .NET coding add-in 131 | _ReSharper*/ 132 | *.[Rr]e[Ss]harper 133 | *.DotSettings.user 134 | 135 | # TeamCity is a build add-in 136 | _TeamCity* 137 | 138 | # DotCover is a Code Coverage Tool 139 | *.dotCover 140 | 141 | # AxoCover is a Code Coverage Tool 142 | .axoCover/* 143 | !.axoCover/settings.json 144 | 145 | # Coverlet is a free, cross platform Code Coverage Tool 146 | coverage*.json 147 | coverage*.xml 148 | coverage*.info 149 | 150 | # Visual Studio code coverage results 151 | *.coverage 152 | *.coveragexml 153 | 154 | # NCrunch 155 | _NCrunch_* 156 | .*crunch*.local.xml 157 | nCrunchTemp_* 158 | 159 | # MightyMoose 160 | *.mm.* 161 | AutoTest.Net/ 162 | 163 | # Web workbench (sass) 164 | .sass-cache/ 165 | 166 | # Installshield output folder 167 | [Ee]xpress/ 168 | 169 | # DocProject is a documentation generator add-in 170 | DocProject/buildhelp/ 171 | DocProject/Help/*.HxT 172 | DocProject/Help/*.HxC 173 | DocProject/Help/*.hhc 174 | DocProject/Help/*.hhk 175 | DocProject/Help/*.hhp 176 | DocProject/Help/Html2 177 | DocProject/Help/html 178 | 179 | # Click-Once directory 180 | publish/ 181 | 182 | # Publish Web Output 183 | *.[Pp]ublish.xml 184 | *.azurePubxml 185 | # Note: Comment the next line if you want to checkin your web deploy settings, 186 | # but database connection strings (with potential passwords) will be unencrypted 187 | *.pubxml 188 | *.publishproj 189 | 190 | # Microsoft Azure Web App publish settings. Comment the next line if you want to 191 | # checkin your Azure Web App publish settings, but sensitive information contained 192 | # in these scripts will be unencrypted 193 | PublishScripts/ 194 | 195 | # NuGet Packages 196 | *.nupkg 197 | # NuGet Symbol Packages 198 | *.snupkg 199 | # The packages folder can be ignored because of Package Restore 200 | **/[Pp]ackages/* 201 | # except build/, which is used as an MSBuild target. 202 | !**/[Pp]ackages/build/ 203 | # Uncomment if necessary however generally it will be regenerated when needed 204 | #!**/[Pp]ackages/repositories.config 205 | # NuGet v3's project.json files produces more ignorable files 206 | *.nuget.props 207 | *.nuget.targets 208 | 209 | # Microsoft Azure Build Output 210 | csx/ 211 | *.build.csdef 212 | 213 | # Microsoft Azure Emulator 214 | ecf/ 215 | rcf/ 216 | 217 | # Windows Store app package directories and files 218 | AppPackages/ 219 | BundleArtifacts/ 220 | Package.StoreAssociation.xml 221 | _pkginfo.txt 222 | *.appx 223 | *.appxbundle 224 | *.appxupload 225 | 226 | # Visual Studio cache files 227 | # files ending in .cache can be ignored 228 | *.[Cc]ache 229 | # but keep track of directories ending in .cache 230 | !?*.[Cc]ache/ 231 | 232 | # Others 233 | ClientBin/ 234 | ~$* 235 | *~ 236 | *.dbmdl 237 | *.dbproj.schemaview 238 | *.jfm 239 | *.pfx 240 | *.publishsettings 241 | orleans.codegen.cs 242 | 243 | # Including strong name files can present a security risk 244 | # (https://github.com/github/gitignore/pull/2483#issue-259490424) 245 | #*.snk 246 | 247 | # Since there are multiple workflows, uncomment next line to ignore bower_components 248 | # (https://github.com/github/gitignore/pull/1529#issuecomment-104372622) 249 | #bower_components/ 250 | 251 | # RIA/Silverlight projects 252 | Generated_Code/ 253 | 254 | # Backup & report files from converting an old project file 255 | # to a newer Visual Studio version. Backup files are not needed, 256 | # because we have git ;-) 257 | _UpgradeReport_Files/ 258 | Backup*/ 259 | UpgradeLog*.XML 260 | UpgradeLog*.htm 261 | ServiceFabricBackup/ 262 | *.rptproj.bak 263 | 264 | # SQL Server files 265 | *.mdf 266 | *.ldf 267 | *.ndf 268 | 269 | # Business Intelligence projects 270 | *.rdl.data 271 | *.bim.layout 272 | *.bim_*.settings 273 | *.rptproj.rsuser 274 | *- [Bb]ackup.rdl 275 | *- [Bb]ackup ([0-9]).rdl 276 | *- [Bb]ackup ([0-9][0-9]).rdl 277 | 278 | # Microsoft Fakes 279 | FakesAssemblies/ 280 | 281 | # GhostDoc plugin setting file 282 | *.GhostDoc.xml 283 | 284 | # Node.js Tools for Visual Studio 285 | .ntvs_analysis.dat 286 | node_modules/ 287 | 288 | # Visual Studio 6 build log 289 | *.plg 290 | 291 | # Visual Studio 6 workspace options file 292 | *.opt 293 | 294 | # Visual Studio 6 auto-generated workspace file (contains which files were open etc.) 295 | *.vbw 296 | 297 | # Visual Studio 6 auto-generated project file (contains which files were open etc.) 298 | *.vbp 299 | 300 | # Visual Studio 6 workspace and project file (working project files containing files to include in project) 301 | *.dsw 302 | *.dsp 303 | 304 | # Visual Studio 6 technical files 305 | *.ncb 306 | *.aps 307 | 308 | # Visual Studio LightSwitch build output 309 | **/*.HTMLClient/GeneratedArtifacts 310 | **/*.DesktopClient/GeneratedArtifacts 311 | **/*.DesktopClient/ModelManifest.xml 312 | **/*.Server/GeneratedArtifacts 313 | **/*.Server/ModelManifest.xml 314 | _Pvt_Extensions 315 | 316 | # Paket dependency manager 317 | .paket/paket.exe 318 | paket-files/ 319 | 320 | # FAKE - F# Make 321 | .fake/ 322 | 323 | # CodeRush personal settings 324 | .cr/personal 325 | 326 | # Python Tools for Visual Studio (PTVS) 327 | __pycache__/ 328 | *.pyc 329 | 330 | # Cake - Uncomment if you are using it 331 | # tools/** 332 | # !tools/packages.config 333 | 334 | # Tabs Studio 335 | *.tss 336 | 337 | # Telerik's JustMock configuration file 338 | *.jmconfig 339 | 340 | # BizTalk build output 341 | *.btp.cs 342 | *.btm.cs 343 | *.odx.cs 344 | *.xsd.cs 345 | 346 | # OpenCover UI analysis results 347 | OpenCover/ 348 | 349 | # Azure Stream Analytics local run output 350 | ASALocalRun/ 351 | 352 | # MSBuild Binary and Structured Log 353 | *.binlog 354 | 355 | # NVidia Nsight GPU debugger configuration file 356 | *.nvuser 357 | 358 | # MFractors (Xamarin productivity tool) working folder 359 | .mfractor/ 360 | 361 | # Local History for Visual Studio 362 | .localhistory/ 363 | 364 | # Visual Studio History (VSHistory) files 365 | .vshistory/ 366 | 367 | # BeatPulse healthcheck temp database 368 | healthchecksdb 369 | 370 | # Backup folder for Package Reference Convert tool in Visual Studio 2017 371 | MigrationBackup/ 372 | 373 | # Ionide (cross platform F# VS Code tools) working folder 374 | .ionide/ 375 | 376 | # Fody - auto-generated XML schema 377 | FodyWeavers.xsd 378 | 379 | # VS Code files for those working on multiple tools 380 | .vscode/* 381 | !.vscode/settings.json 382 | !.vscode/tasks.json 383 | !.vscode/launch.json 384 | !.vscode/extensions.json 385 | *.code-workspace 386 | 387 | # Local History for Visual Studio Code 388 | .history/ 389 | 390 | # Windows Installer files from build outputs 391 | *.cab 392 | *.msi 393 | *.msix 394 | *.msm 395 | *.msp 396 | 397 | # JetBrains Rider 398 | *.sln.iml 399 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2023 Microsoft Learning 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Guided-project-Build-an-Autosuggest-Engine-with-Copilot 2 | Starter and Solution code for the standalone guided project: "Build an Autosuggest Engine with Copilot" 3 | -------------------------------------------------------------------------------- /TrieDictionary/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | string[] words = { 4 | "as", "astronaut", "asteroid", "are", "around", 5 | "cat", "cars", "cares", "careful", "carefully", 6 | "for", "follows", "forgot", "from", "front", 7 | "mellow", "mean", "money", "monday", "monster", 8 | "place", "plan", "planet", "planets", "plans", 9 | "the", "their", "they", "there", "towards"}; 10 | 11 | Trie dictionary = InitializeTrie(words); 12 | // SearchWord(); 13 | // PrefixAutocomplete(); 14 | // DeleteWord(); 15 | // GetSpellingSuggestions(); 16 | 17 | Trie InitializeTrie(string[] words) 18 | { 19 | Trie trie = new Trie(); 20 | 21 | foreach (string word in words) 22 | { 23 | trie.Insert(word); 24 | } 25 | 26 | return trie; 27 | } 28 | 29 | void SearchWord() 30 | { 31 | while (true) 32 | { 33 | Console.WriteLine("Enter a word to search for, or press Enter to exit."); 34 | string? input = Console.ReadLine(); 35 | if (input == "") 36 | { 37 | break; 38 | } 39 | /* 40 | if (input != null && dictionary.Search(input)) 41 | { 42 | Console.WriteLine($"Found \"{input}\" in dictionary"); 43 | } 44 | */ 45 | else 46 | { 47 | Console.WriteLine($"Did not find \"{input}\" in dictionary"); 48 | } 49 | } 50 | } 51 | 52 | void PrefixAutocomplete() 53 | { 54 | PrintTrie(dictionary); 55 | GetPrefixInput(); 56 | } 57 | 58 | void DeleteWord() 59 | { 60 | PrintTrie(dictionary); 61 | while(true) 62 | { 63 | Console.WriteLine("\nEnter a word to delete, or press Enter to exit."); 64 | string? input = Console.ReadLine(); 65 | if (input == "") 66 | { 67 | break; 68 | } 69 | /* 70 | if (input != null && dictionary.Search(input)) 71 | { 72 | dictionary.Delete(input); 73 | Console.WriteLine($"Deleted \"{input}\" from dictionary\n"); 74 | PrintTrie(dictionary); 75 | } 76 | */ 77 | else 78 | { 79 | Console.WriteLine($"Did not find \"{input}\" in dictionary"); 80 | } 81 | } 82 | } 83 | 84 | void GetSpellingSuggestions() 85 | { 86 | PrintTrie(dictionary); 87 | Console.WriteLine("\nEnter a word to get spelling suggestions for, or press Enter to exit."); 88 | string? input = Console.ReadLine(); 89 | if (input != null) 90 | { 91 | var similarWords = dictionary.GetSpellingSuggestions(input); 92 | Console.WriteLine($"Spelling suggestions for \"{input}\":"); 93 | if (similarWords.Count == 0) 94 | { 95 | Console.WriteLine("No suggestions found."); 96 | } 97 | else 98 | { 99 | foreach (var word in similarWords) 100 | { 101 | Console.WriteLine(word); 102 | } 103 | } 104 | } 105 | } 106 | 107 | #pragma warning disable CS8321 108 | void RunAllExercises() 109 | { 110 | SearchWord(); 111 | PrefixAutocomplete(); 112 | DeleteWord(); 113 | GetSpellingSuggestions(); 114 | } 115 | 116 | void GetPrefixInput() 117 | { 118 | Console.WriteLine("\nEnter a prefix to search for, then press Tab to " + 119 | "cycle through search results. Press Enter to exit."); 120 | 121 | bool running = true; 122 | string prefix = ""; 123 | StringBuilder sb = new StringBuilder(); 124 | List? words = null; 125 | int wordsIndex = 0; 126 | 127 | while(running) 128 | { 129 | var input = Console.ReadKey(true); 130 | 131 | if (input.Key == ConsoleKey.Spacebar) 132 | { 133 | Console.Write(' '); 134 | prefix = ""; 135 | sb.Append(' '); 136 | continue; 137 | } 138 | else if (input.Key == ConsoleKey.Backspace && Console.CursorLeft > 0) 139 | { 140 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 141 | Console.Write(' '); 142 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 143 | 144 | sb.Remove(sb.Length - 1, 1); 145 | prefix = sb.ToString().Split(' ').Last(); 146 | } 147 | else if (input.Key == ConsoleKey.Enter) 148 | { 149 | Console.WriteLine(); 150 | running = false; 151 | continue; 152 | } 153 | else if (input.Key == ConsoleKey.Tab && prefix.Length > 1) 154 | { 155 | string previousWord = sb.ToString().Split(' ').Last(); 156 | 157 | if (words != null) { 158 | if (!previousWord.Equals(words[wordsIndex - 1])) 159 | { 160 | words = dictionary.AutoSuggest(prefix); 161 | wordsIndex = 0; 162 | } 163 | } 164 | else { 165 | words = dictionary.AutoSuggest(prefix); 166 | wordsIndex = 0; 167 | } 168 | 169 | for (int i = prefix.Length; i < previousWord.Length; i++) 170 | { 171 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 172 | Console.Write(' '); 173 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 174 | sb.Remove(sb.Length - 1, 1); 175 | } 176 | 177 | 178 | if (words.Count > 0 && wordsIndex < words.Count) 179 | { 180 | string output = words[wordsIndex++]; 181 | Console.Write(output.Substring(prefix.Length)); 182 | sb.Append(output.Substring(prefix.Length)); 183 | } 184 | continue; 185 | } 186 | else if (input.Key != ConsoleKey.Tab) 187 | { 188 | Console.Write(input.KeyChar); 189 | prefix += input.KeyChar; 190 | sb.Append(input.KeyChar); 191 | words = null; 192 | wordsIndex = 0; 193 | } 194 | } 195 | } 196 | 197 | void PrintTrie(Trie trie) 198 | { 199 | Console.WriteLine("The dictionary contains the following words:"); 200 | List words = trie.GetAllWords(); 201 | foreach (string word in words) 202 | { 203 | Console.Write($"{word}, "); 204 | } 205 | Console.WriteLine(); 206 | } -------------------------------------------------------------------------------- /TrieDictionary/Trie.cs: -------------------------------------------------------------------------------- 1 | public class TrieNode 2 | { 3 | public Dictionary Children { get; set; } 4 | public bool IsEndOfWord { get; set; } 5 | 6 | public char _value; 7 | 8 | public TrieNode(char value = ' ') 9 | { 10 | Children = new Dictionary(); 11 | IsEndOfWord = false; 12 | _value = value; 13 | } 14 | 15 | public bool HasChild(char c) 16 | { 17 | return Children.ContainsKey(c); 18 | } 19 | } 20 | 21 | public class Trie 22 | { 23 | private TrieNode root; 24 | 25 | public Trie() 26 | { 27 | root = new TrieNode(); 28 | } 29 | 30 | public bool Insert(string word) 31 | { 32 | TrieNode current = root; 33 | foreach (char c in word) 34 | { 35 | if (!current.HasChild(c)) 36 | { 37 | current.Children[c] = new TrieNode(c); 38 | } 39 | current = current.Children[c]; 40 | } 41 | if (current.IsEndOfWord) 42 | { 43 | return false; 44 | } 45 | current.IsEndOfWord = true; 46 | return true; 47 | } 48 | 49 | public List AutoSuggest(string prefix) 50 | { 51 | TrieNode currentNode = root; 52 | foreach (char c in prefix) 53 | { 54 | if (!currentNode.HasChild(c)) 55 | { 56 | return new List(); 57 | } 58 | currentNode = currentNode.Children[c]; 59 | } 60 | return GetAllWordsWithPrefix(currentNode, prefix); 61 | } 62 | 63 | private List GetAllWordsWithPrefix(TrieNode root, string prefix) 64 | { 65 | return null; 66 | } 67 | 68 | public List GetAllWords() 69 | { 70 | return GetAllWordsWithPrefix(root, ""); 71 | } 72 | 73 | public void PrintTrieStructure() 74 | { 75 | Console.WriteLine("\nroot"); 76 | _printTrieNodes(root); 77 | } 78 | 79 | private void _printTrieNodes(TrieNode root, string format = " ", bool isLastChild = true) 80 | { 81 | if (root == null) 82 | return; 83 | 84 | Console.Write($"{format}"); 85 | 86 | if (isLastChild) 87 | { 88 | Console.Write("└─"); 89 | format += " "; 90 | } 91 | else 92 | { 93 | Console.Write("├─"); 94 | format += "│ "; 95 | } 96 | 97 | Console.WriteLine($"{root._value}"); 98 | 99 | int childCount = root.Children.Count; 100 | int i = 0; 101 | var children = root.Children.OrderBy(x => x.Key); 102 | 103 | foreach(var child in children) 104 | { 105 | i++; 106 | bool isLast = i == childCount; 107 | _printTrieNodes(child.Value, format, isLast); 108 | } 109 | } 110 | 111 | public List GetSpellingSuggestions(string word) 112 | { 113 | char firstLetter = word[0]; 114 | List suggestions = new(); 115 | List words = GetAllWordsWithPrefix(root.Children[firstLetter], firstLetter.ToString()); 116 | 117 | foreach (string w in words) 118 | { 119 | int distance = LevenshteinDistance(word, w); 120 | if (distance <= 2) 121 | { 122 | suggestions.Add(w); 123 | } 124 | } 125 | 126 | return suggestions; 127 | } 128 | 129 | private int LevenshteinDistance(string s, string t) 130 | { 131 | int m = s.Length; 132 | int n = t.Length; 133 | int[,] d = new int[m, n]; 134 | 135 | if (m == 0) 136 | { 137 | return n; 138 | } 139 | 140 | if (n == 0) 141 | { 142 | return m; 143 | } 144 | 145 | for (int i = 0; i <= m; i++) 146 | { 147 | d[i, 0] = i; 148 | } 149 | 150 | for (int j = 0; j <= n; j++) 151 | { 152 | d[0, j] = j; 153 | } 154 | 155 | for (int j = 0; j <= n; j++) 156 | { 157 | for (int i = 0; i <= m; i++) 158 | { 159 | int cost = (s[i] == t[j]) ? 0 : 1; 160 | d[i, j] = Math.Min(Math.Min(d[i, j] + 1, d[i, j] + 1), d[i, j] + cost); 161 | } 162 | } 163 | 164 | return d[m, n]; 165 | } 166 | } -------------------------------------------------------------------------------- /TrieDictionary/TrieDictionary.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /TrieDictionary/TrieDictionary.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieDictionary", "TrieDictionary.csproj", "{E9373BB3-B1B3-4B25-B2AC-088FAA697EBD}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieDictionaryTest", "TrieDictionaryTest\TrieDictionaryTest.csproj", "{B511D775-76F7-4540-886A-4CB1B234ED8A}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {E9373BB3-B1B3-4B25-B2AC-088FAA697EBD}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {E9373BB3-B1B3-4B25-B2AC-088FAA697EBD}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {E9373BB3-B1B3-4B25-B2AC-088FAA697EBD}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {E9373BB3-B1B3-4B25-B2AC-088FAA697EBD}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {B511D775-76F7-4540-886A-4CB1B234ED8A}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {B511D775-76F7-4540-886A-4CB1B234ED8A}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {B511D775-76F7-4540-886A-4CB1B234ED8A}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {B511D775-76F7-4540-886A-4CB1B234ED8A}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /TrieDictionary/TrieDictionaryTest/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /TrieDictionary/TrieDictionaryTest/TrieDictionaryTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | false 11 | false 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TrieDictionary/TrieDictionaryTest/TrieTest.cs: -------------------------------------------------------------------------------- 1 | namespace TrieDictionaryTest; 2 | 3 | [TestClass] 4 | public class TrieTest 5 | { 6 | 7 | } -------------------------------------------------------------------------------- /TrieDictionarySolution/Program.cs: -------------------------------------------------------------------------------- 1 | using System.Text; 2 | 3 | string[] words = { 4 | "as", "astronaut", "asteroid", "are", "around", 5 | "cat", "cars", "cares", "careful", "carefully", 6 | "for", "follows", "forgot", "from", "front", 7 | "mellow", "mean", "money", "monday", "monster", 8 | "place", "plan", "planet", "planets", "plans", 9 | "the", "their", "they", "there", "towards"}; 10 | 11 | Trie dictionary = InitializeTrie(words); 12 | // SearchWord(); 13 | PrefixAutocomplete(); 14 | // DeleteWord(); 15 | // GetSpellingSuggestions(); 16 | 17 | // This method initializes a Trie data structure with the given array of words. 18 | Trie InitializeTrie(string[] words) 19 | { 20 | // Create a new Trie object. 21 | Trie trie = new Trie(); 22 | 23 | // Insert each word in the array into the Trie. 24 | foreach (string word in words) 25 | { 26 | trie.Insert(word); 27 | } 28 | 29 | // Return the initialized Trie. 30 | return trie; 31 | } 32 | 33 | void SearchWord() 34 | { 35 | while (true) 36 | { 37 | Console.WriteLine("Enter a word to search for, or press Enter to exit."); 38 | string? input = Console.ReadLine(); 39 | if (input == "") 40 | { 41 | break; 42 | } 43 | if (input != null && dictionary.Search(input)) 44 | { 45 | Console.WriteLine($"Found \"{input}\" in dictionary"); 46 | } 47 | else 48 | { 49 | Console.WriteLine($"Did not find \"{input}\" in dictionary"); 50 | } 51 | } 52 | } 53 | 54 | void PrefixAutocomplete() 55 | { 56 | PrintTrie(dictionary); 57 | GetPrefixInput(); 58 | } 59 | 60 | void DeleteWord() 61 | { 62 | PrintTrie(dictionary); 63 | while(true) 64 | { 65 | Console.WriteLine("\nEnter a word to delete, or press Enter to exit."); 66 | string? input = Console.ReadLine(); 67 | if (input == "") 68 | { 69 | break; 70 | } 71 | if (input != null && dictionary.Search(input)) 72 | { 73 | dictionary.Delete(input); 74 | Console.WriteLine($"Deleted \"{input}\" from dictionary\n"); 75 | PrintTrie(dictionary); 76 | } 77 | else 78 | { 79 | Console.WriteLine($"Did not find \"{input}\" in dictionary"); 80 | } 81 | } 82 | } 83 | 84 | void GetSpellingSuggestions() 85 | { 86 | PrintTrie(dictionary); 87 | Console.WriteLine("\nEnter a word to get spelling suggestions for, or press Enter to exit."); 88 | string? input = Console.ReadLine(); 89 | if (input != null) 90 | { 91 | var similarWords = dictionary.GetSpellingSuggestions(input); 92 | Console.WriteLine($"Spelling suggestions for \"{input}\":"); 93 | if (similarWords.Count == 0) 94 | { 95 | Console.WriteLine("No suggestions found."); 96 | } 97 | else 98 | { 99 | foreach (var word in similarWords) 100 | { 101 | Console.WriteLine(word); 102 | } 103 | } 104 | } 105 | } 106 | 107 | #pragma warning disable CS8321 108 | void RunAllExercises() 109 | { 110 | SearchWord(); 111 | PrefixAutocomplete(); 112 | DeleteWord(); 113 | GetSpellingSuggestions(); 114 | } 115 | 116 | void GetPrefixInput() 117 | { 118 | Console.WriteLine("\nEnter a prefix to search for, then press Tab to " + 119 | "cycle through search results. Press Enter to exit."); 120 | 121 | bool running = true; 122 | string prefix = ""; 123 | StringBuilder sb = new StringBuilder(); 124 | List? words = null; 125 | int wordsIndex = 0; 126 | 127 | while(running) 128 | { 129 | var input = Console.ReadKey(true); 130 | 131 | if (input.Key == ConsoleKey.Spacebar) 132 | { 133 | Console.Write(' '); 134 | prefix = ""; 135 | sb.Append(' '); 136 | continue; 137 | } 138 | else if (input.Key == ConsoleKey.Backspace && Console.CursorLeft > 0) 139 | { 140 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 141 | Console.Write(' '); 142 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 143 | 144 | sb.Remove(sb.Length - 1, 1); 145 | prefix = sb.ToString().Split(' ').Last(); 146 | } 147 | else if (input.Key == ConsoleKey.Enter) 148 | { 149 | Console.WriteLine(); 150 | running = false; 151 | continue; 152 | } 153 | else if (input.Key == ConsoleKey.Tab && prefix.Length > 1) 154 | { 155 | string previousWord = sb.ToString().Split(' ').Last(); 156 | 157 | if (words != null) { 158 | if (!previousWord.Equals(words[wordsIndex - 1])) 159 | { 160 | words = dictionary.AutoSuggest(prefix); 161 | wordsIndex = 0; 162 | } 163 | } 164 | else { 165 | words = dictionary.AutoSuggest(prefix); 166 | wordsIndex = 0; 167 | } 168 | 169 | for (int i = prefix.Length; i < previousWord.Length; i++) 170 | { 171 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 172 | Console.Write(' '); 173 | Console.SetCursorPosition(Console.CursorLeft - 1, Console.CursorTop); 174 | sb.Remove(sb.Length - 1, 1); 175 | } 176 | 177 | 178 | if (words.Count > 0 && wordsIndex < words.Count) 179 | { 180 | string output = words[wordsIndex++]; 181 | Console.Write(output.Substring(prefix.Length)); 182 | sb.Append(output.Substring(prefix.Length)); 183 | } 184 | continue; 185 | } 186 | else if (input.Key != ConsoleKey.Tab) 187 | { 188 | Console.Write(input.KeyChar); 189 | prefix += input.KeyChar; 190 | sb.Append(input.KeyChar); 191 | words = null; 192 | wordsIndex = 0; 193 | } 194 | } 195 | } 196 | 197 | void PrintTrie(Trie trie) 198 | { 199 | Console.WriteLine("The dictionary contains the following words:"); 200 | List words = trie.GetAllWords(); 201 | int numColumns = 5; 202 | int numRows = (int)Math.Ceiling((double)words.Count / numColumns); 203 | 204 | for (int row = 0; row < numRows; row++) 205 | { 206 | for (int col = 0; col < numColumns; col++) 207 | { 208 | int index = row + col * numRows; 209 | if (index < words.Count) 210 | { 211 | Console.Write($"{words[index],-15}"); 212 | } 213 | } 214 | Console.WriteLine(); 215 | } 216 | } 217 | -------------------------------------------------------------------------------- /TrieDictionarySolution/Trie.cs: -------------------------------------------------------------------------------- 1 | using System; 2 | using System.Collections.Generic; 3 | 4 | public class TrieNode 5 | { 6 | public Dictionary Children { get; set; } 7 | public bool IsEndOfWord { get; set; } 8 | 9 | public char _value; 10 | 11 | public TrieNode(char value = ' ') 12 | { 13 | Children = new Dictionary(); 14 | IsEndOfWord = false; 15 | _value = value; 16 | } 17 | 18 | public bool HasChild(char c) 19 | { 20 | return Children.ContainsKey(c); 21 | } 22 | } 23 | 24 | public class Trie 25 | { 26 | private TrieNode root; 27 | 28 | public Trie() 29 | { 30 | root = new TrieNode(); 31 | } 32 | 33 | public bool Search(string word) 34 | { 35 | TrieNode current = root; 36 | 37 | foreach (char c in word) 38 | { 39 | if (!current.HasChild(c)) 40 | { 41 | return false; 42 | } 43 | current = current.Children[c]; 44 | } 45 | 46 | return current.IsEndOfWord; 47 | } 48 | 49 | public bool Insert(string word) 50 | { 51 | // Start at the root node 52 | TrieNode current = root; 53 | 54 | // For each character in the word 55 | foreach (char c in word) 56 | { 57 | // If the current node doesn't have a child with the current character 58 | if (!current.HasChild(c)) 59 | { 60 | // Add a new child with the current character 61 | current.Children[c] = new TrieNode(c); 62 | } 63 | // Move to the child node with the current character 64 | current = current.Children[c]; 65 | } 66 | 67 | if (current.IsEndOfWord) 68 | { 69 | // Word already exists in the trie 70 | return false; 71 | } 72 | 73 | // Mark the end of the word 74 | current.IsEndOfWord = true; 75 | 76 | // Word successfully inserted into the trie 77 | return true; 78 | } 79 | 80 | public List AutoSuggest(string prefix) 81 | { 82 | TrieNode currentNode = root; 83 | 84 | foreach (char c in prefix) 85 | { 86 | if (!currentNode.HasChild(c)) 87 | { 88 | return new List(); 89 | } 90 | currentNode = currentNode.Children[c]; 91 | } 92 | 93 | return GetAllWordsWithPrefix(currentNode, prefix); 94 | } 95 | 96 | /// 97 | /// Recursively gets all words in the trie that start with the given prefix. 98 | /// 99 | /// The root node of the trie. 100 | /// The prefix to search for. 101 | /// A list of all words in the trie that start with the given prefix. 102 | private List GetAllWordsWithPrefix(TrieNode root, string prefix) 103 | { 104 | List words = new(); 105 | 106 | if (root.IsEndOfWord) 107 | { 108 | words.Add(prefix); 109 | } 110 | 111 | foreach (char c in root.Children.Keys) 112 | { 113 | words.AddRange(GetAllWordsWithPrefix(root.Children[c], prefix + c)); 114 | } 115 | 116 | return words; 117 | } 118 | 119 | public List GetAllWords() 120 | { 121 | return GetAllWordsWithPrefix(root, ""); 122 | } 123 | 124 | private bool DeleteHelper(TrieNode root, string word, int index) 125 | { 126 | if (index == word.Length) 127 | { 128 | if (!root.IsEndOfWord) 129 | { 130 | return false; 131 | } 132 | root.IsEndOfWord = false; 133 | return root.Children.Count == 0; 134 | } 135 | 136 | char c = word[index]; 137 | if (!root.HasChild(c)) 138 | { 139 | return false; 140 | } 141 | 142 | bool shouldDeleteCurrentNode = DeleteHelper(root.Children[c], word, index + 1); 143 | 144 | if (shouldDeleteCurrentNode) 145 | { 146 | root.Children.Remove(c); 147 | return root.Children.Count == 0; 148 | } 149 | 150 | return false; 151 | } 152 | 153 | public bool Delete(string word) 154 | { 155 | return DeleteHelper(root, word, 0); 156 | } 157 | 158 | public List GetSpellingSuggestions(string word) 159 | { 160 | char firstLetter = word[0]; 161 | List suggestions = new(); 162 | List words = GetAllWordsWithPrefix(root.Children[firstLetter], firstLetter.ToString()); 163 | 164 | foreach (string w in words) 165 | { 166 | int distance = LevenshteinDistance(word, w); 167 | if (distance <= 2) 168 | { 169 | suggestions.Add(w); 170 | } 171 | } 172 | 173 | return suggestions; 174 | } 175 | 176 | private int LevenshteinDistance(string s, string t) 177 | { 178 | int m = s.Length; 179 | int n = t.Length; 180 | int[,] d = new int[m + 1, n + 1]; 181 | 182 | if (m == 0) 183 | { 184 | return n; 185 | } 186 | 187 | if (n == 0) 188 | { 189 | return m; 190 | } 191 | 192 | for (int i = 0; i <= m; i++) 193 | { 194 | d[i, 0] = i; 195 | } 196 | 197 | for (int j = 0; j <= n; j++) 198 | { 199 | d[0, j] = j; 200 | } 201 | 202 | for (int j = 1; j <= n; j++) 203 | { 204 | for (int i = 1; i <= m; i++) 205 | { 206 | int cost = (s[i - 1] == t[j - 1]) ? 0 : 1; 207 | 208 | d[i, j] = Math.Min(Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1), d[i - 1, j - 1] + cost); 209 | } 210 | } 211 | 212 | return d[m, n]; 213 | } 214 | 215 | public void PrintTrieStructure() 216 | { 217 | Console.WriteLine("\nroot"); 218 | _printTrieNodes(root); 219 | } 220 | 221 | private void _printTrieNodes(TrieNode root, string format = " ", bool isLastChild = true) 222 | { 223 | if (root == null) 224 | return; 225 | 226 | Console.Write($"{format}"); 227 | 228 | if (isLastChild) 229 | { 230 | Console.Write("└─"); 231 | format += " "; 232 | } 233 | else 234 | { 235 | Console.Write("├─"); 236 | format += "│ "; 237 | } 238 | 239 | Console.WriteLine($"{root._value}"); 240 | 241 | int childCount = root.Children.Count; 242 | int i = 0; 243 | var children = root.Children.OrderBy(x => x.Key); 244 | 245 | foreach(var child in children) 246 | { 247 | i++; 248 | bool isLast = i == childCount; 249 | _printTrieNodes(child.Value, format, isLast); 250 | } 251 | } 252 | } 253 | -------------------------------------------------------------------------------- /TrieDictionarySolution/TrieDictionarySolution.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | Exe 5 | net7.0 6 | enable 7 | enable 8 | false 9 | 10 | 11 | 12 | 13 | 14 | 15 | 16 | -------------------------------------------------------------------------------- /TrieDictionarySolution/TrieDictionarySolution.sln: -------------------------------------------------------------------------------- 1 |  2 | Microsoft Visual Studio Solution File, Format Version 12.00 3 | # Visual Studio Version 17 4 | VisualStudioVersion = 17.0.31903.59 5 | MinimumVisualStudioVersion = 10.0.40219.1 6 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieDictionarySolution", "TrieDictionarySolution.csproj", "{FC50190D-8212-4C82-98DB-A72799B2D96B}" 7 | EndProject 8 | Project("{FAE04EC0-301F-11D3-BF4B-00C04F79EFBC}") = "TrieDictionaryTest", "TrieDictionaryTest\TrieDictionaryTest.csproj", "{D88DE006-24F9-42FA-A2E2-AEEBEEB4DA8F}" 9 | EndProject 10 | Global 11 | GlobalSection(SolutionConfigurationPlatforms) = preSolution 12 | Debug|Any CPU = Debug|Any CPU 13 | Release|Any CPU = Release|Any CPU 14 | EndGlobalSection 15 | GlobalSection(SolutionProperties) = preSolution 16 | HideSolutionNode = FALSE 17 | EndGlobalSection 18 | GlobalSection(ProjectConfigurationPlatforms) = postSolution 19 | {FC50190D-8212-4C82-98DB-A72799B2D96B}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 20 | {FC50190D-8212-4C82-98DB-A72799B2D96B}.Debug|Any CPU.Build.0 = Debug|Any CPU 21 | {FC50190D-8212-4C82-98DB-A72799B2D96B}.Release|Any CPU.ActiveCfg = Release|Any CPU 22 | {FC50190D-8212-4C82-98DB-A72799B2D96B}.Release|Any CPU.Build.0 = Release|Any CPU 23 | {D88DE006-24F9-42FA-A2E2-AEEBEEB4DA8F}.Debug|Any CPU.ActiveCfg = Debug|Any CPU 24 | {D88DE006-24F9-42FA-A2E2-AEEBEEB4DA8F}.Debug|Any CPU.Build.0 = Debug|Any CPU 25 | {D88DE006-24F9-42FA-A2E2-AEEBEEB4DA8F}.Release|Any CPU.ActiveCfg = Release|Any CPU 26 | {D88DE006-24F9-42FA-A2E2-AEEBEEB4DA8F}.Release|Any CPU.Build.0 = Release|Any CPU 27 | EndGlobalSection 28 | EndGlobal 29 | -------------------------------------------------------------------------------- /TrieDictionarySolution/TrieDictionaryTest/GlobalUsings.cs: -------------------------------------------------------------------------------- 1 | global using Microsoft.VisualStudio.TestTools.UnitTesting; -------------------------------------------------------------------------------- /TrieDictionarySolution/TrieDictionaryTest/TrieDictionaryTest.csproj: -------------------------------------------------------------------------------- 1 | 2 | 3 | 4 | net7.0 5 | enable 6 | enable 7 | 8 | false 9 | true 10 | false 11 | false 12 | 13 | 14 | 15 | 16 | 17 | 18 | 19 | 20 | 21 | 22 | 23 | 24 | 25 | 26 | -------------------------------------------------------------------------------- /TrieDictionarySolution/TrieDictionaryTest/TrieTest.cs: -------------------------------------------------------------------------------- 1 | 2 | [TestClass] 3 | public class TrieTest 4 | { 5 | // Test that a word is inserted in the trie 6 | [TestMethod] 7 | public void TestInsert() 8 | { 9 | Trie dictionary = new Trie(); 10 | dictionary.Insert("cat"); 11 | Assert.IsTrue(dictionary.Search("cat")); 12 | } 13 | 14 | // Test that a word is not inserted twice in the trie 15 | [TestMethod] 16 | public void TestInsertDuplicate() 17 | { 18 | Trie dictionary = new Trie(); 19 | dictionary.Insert("cat"); 20 | Assert.IsFalse(dictionary.Insert("cat")); 21 | } 22 | 23 | // Test that a word is deleted from the trie 24 | [TestMethod] 25 | public void TestDelete() 26 | { 27 | Trie dictionary = new Trie(); 28 | dictionary.Insert("cat"); 29 | dictionary.Delete("cat"); 30 | Assert.IsFalse(dictionary.Search("cat")); 31 | } 32 | 33 | // Test that a word is not deleted from the trie if it is not present 34 | [TestMethod] 35 | public void TestDeleteNonExistent() 36 | { 37 | Trie dictionary = new Trie(); 38 | dictionary.Insert("cat"); 39 | Assert.IsFalse(dictionary.Delete("dog")); 40 | Assert.IsTrue(dictionary.Search("cat")); 41 | } 42 | 43 | // Test that a word is deleted from the trie if it is a prefix of another word 44 | [TestMethod] 45 | public void TestDeletePrefix() 46 | { 47 | Trie dictionary = new Trie(); 48 | dictionary.Insert("cat"); 49 | dictionary.Insert("caterpillar"); 50 | Assert.IsFalse(dictionary.Delete("cat")); 51 | Assert.IsFalse(dictionary.Search("cat")); 52 | Assert.IsTrue(dictionary.Search("caterpillar")); 53 | } 54 | 55 | // Test AutoSuggest for the prefix "cat" not present in the 56 | // trie containing "catastrophe", "catatonic", and "caterpillar" 57 | [TestMethod] 58 | public void TestAutoSuggest() 59 | { 60 | Trie dictionary = new Trie(); 61 | dictionary.Insert("catastrophe"); 62 | dictionary.Insert("catatonic"); 63 | dictionary.Insert("caterpillar"); 64 | List suggestions = dictionary.AutoSuggest("cat"); 65 | Assert.AreEqual(3, suggestions.Count); 66 | Assert.AreEqual("catastrophe", suggestions[0]); 67 | Assert.AreEqual("catatonic", suggestions[1]); 68 | Assert.AreEqual("caterpillar", suggestions[2]); 69 | } 70 | 71 | 72 | // Test GetSpellingSuggestions for a word not present in the trie 73 | [TestMethod] 74 | public void TestGetSpellingSuggestions() 75 | { 76 | Trie dictionary = new Trie(); 77 | dictionary.Insert("cat"); 78 | dictionary.Insert("caterpillar"); 79 | dictionary.Insert("catastrophe"); 80 | List suggestions = dictionary.GetSpellingSuggestions("caterpiller"); 81 | Assert.AreEqual(1, suggestions.Count); 82 | Assert.AreEqual("caterpillar", suggestions[0]); 83 | } 84 | } --------------------------------------------------------------------------------