public static void LoadDictionary(Action <double> progress) { try { using (var stream = new FileStream("dictionary.txt", FileMode.Open)) { using (var reader = new StreamReader(stream)) { var initLine = reader.ReadLine(); Levenshtein.tree = new DistanceTree(new DistanceTree.Node(initLine, new List <DistanceTree.Edge>())); while (!reader.EndOfStream) { var line = reader.ReadLine(); if (string.IsNullOrWhiteSpace(line)) { continue; } Levenshtein.AddToTree(line.ToUpper()); progress?.Invoke(stream.Position / (double)stream.Length); } } } } catch (Exception ex) { Console.WriteLine(ex.Message); } }
public MainWindow() { this.InitializeComponent(); Task.Run(() => { Levenshtein.LoadDictionary(p => { this.Dispatcher.Invoke(() => { this.ProgressBar.Value = p * 100; this.LabelLoading.Content = $"Loading dictionary: {Math.Round(p*100, 2)} %"; }); }); this.Dispatcher.Invoke(() => { this.ProgressBar.Visibility = Visibility.Collapsed; this.LabelLoading.Visibility = Visibility.Collapsed; this.InputField.Visibility = Visibility.Visible; this.HintText.Visibility = Visibility.Visible; this.ListSimilar.Visibility = Visibility.Visible; }); }); }
private void InputField_TextChanged(object sender, TextChangedEventArgs e) { this.ListSimilar.Items.Clear(); if (!string.IsNullOrWhiteSpace(this.InputField.Text)) { foreach (var similar in Levenshtein.FindSimilar(this.InputField.Text)) { this.ListSimilar.Items.Add(similar); } } }
private static void FindSimilar(DistanceTree.Node node, int radius, List <DistanceTree.Node> nodes, int distance, int searchRadius) { if (radius > searchRadius) { return; } node.Cache = distance; nodes.Add(node); foreach (var edge in node.Edges) { Levenshtein.FindSimilar(edge.End, radius + 1, nodes, distance + edge.Distance, searchRadius); } }
public static IEnumerable <string> FindSimilar(string s) { var ss = s.ToUpper(); var searchRadius = Math.Min(s.Length - 2, Levenshtein.MAX_RADIUS); if (!Levenshtein.NodeDictionary.ContainsKey(ss) || searchRadius == 0) { return(new string[0]); } var node = Levenshtein.NodeDictionary[ss]; var retval = new List <DistanceTree.Node>(); Levenshtein.FindSimilar(node, 0, retval, 0, searchRadius); return(retval.Distinct().Where(x => x.Cache <= searchRadius && x.Content != ss).OrderBy(x => x.Cache).Select(x => x.Content.ToLower())); }