Exemplo n.º 1
0
        public ActionResult <IEnumerable <string> > Get()
        {
            var        stringDistance = new StringDistance();
            var        watch          = new Stopwatch();
            const long count          = 100;
            const int  length         = 100;
            string     comparestring  = stringDistance.GenerateRandomString(length);
            var        strlist        = new string[count];
            var        steps          = new int[count];

            // prepare string[] for comparison

            Parallel.For(0, count, i => strlist[i] = stringDistance.GenerateRandomString(length));
            Console.WriteLine("已经生成了" + count + "个长度为" + length + "的字符串");

            watch.Start();
            for (int i = 0; i < count; i++)
            {
                steps[i] = stringDistance.LevenshteinDistance(comparestring, strlist[i]);
            }
            watch.Stop();
            Console.WriteLine("完成非并行计算,耗时(ms)" + watch.ElapsedMilliseconds);
            Console.WriteLine("性能比" + 100000d / watch.ElapsedMilliseconds);

            return(Ok("0.0.1"));
        }
        private static int GetDistance(UserInfo user, string word1, string word2)
        {
            var distance1 = StringDistance.LevenshteinDistance(user.FirstName, word1) + StringDistance.LevenshteinDistance(user.LastName, word2);
            var distance2 = StringDistance.LevenshteinDistance(user.FirstName, word2) + StringDistance.LevenshteinDistance(user.LastName, word1);

            return(Math.Min(distance1, distance2));
        }
Exemplo n.º 3
0
        private void btnOutput_Click(object sender, EventArgs e)
        {
            using (StreamReader r = new StreamReader("cities.json"))
            {
                string      json  = r.ReadToEnd();
                List <Item> items = JsonConvert.DeserializeObject <List <Item> >(json);

                items = items.Where(x => x.country.Equals("ID")).ToList();

                string input = txtInput.Text;
                int    hasil;
                string hasiloutput = "";

                for (var i = 0; i < items.Count; i++)
                {
                    hasil = StringDistance.LevenshteinDistance(input.ToLower(), items[i].name.ToLower());

                    decimal persenPerubahan = 0;



                    persenPerubahan = ((decimal)hasil / (decimal)input.Length) * 100;

                    if (persenPerubahan <= 30)
                    {
                        hasiloutput += items[i].name + " (" + persenPerubahan + ")" + " ,";
                    }
                }


                txtOutput.Text = hasiloutput;
            }

            MessageBox.Show("Done!");
        }
Exemplo n.º 4
0
    public static IEnumerable <R> JoinSimilar <T, S, R>(this List <T> outer, List <S> inner,
                                                        Func <T, string> outerKeySelector,
                                                        Func <S, string> innerKeySelector,
                                                        Func <T, S, int, R> resultSelector)
        where T : notnull
        where S : notnull
    {
        StringDistance sd = new StringDistance();
        Dictionary <Tuple <T, S>, int> distances = (from o in outer
                                                    from i in inner
                                                    select KeyValuePair.Create(Tuple.Create(o, i),
                                                                               sd.LevenshteinDistance(outerKeySelector(o), innerKeySelector(i)))).ToDictionary();

        while (distances.Count > 0)
        {
            var kvp   = distances.MinBy(a => a.Value);
            var tuple = kvp.Key;

            distances.RemoveRange(distances.Keys.Where(a => a.Item1.Equals(tuple.Item1) || a.Item2.Equals(tuple.Item2)).ToList());
            outer.Remove(tuple.Item1);
            inner.Remove(tuple.Item2);

            yield return(resultSelector(tuple.Item1, tuple.Item2, kvp.Value));
        }
    }
Exemplo n.º 5
0
    WithDescription <V>?TryGetValue(string input)
    {
        var exact = dictionary.TryGetC(input);

        if (exact != null)
        {
            return(exact);
        }

        var sd   = new StringDistance();
        var best = dictionary.Keys.MinBy(a => sd.LevenshteinDistance(input.ToLowerInvariant(), a.ToLowerInvariant()));

        if (best != null && sd.LevenshteinDistance(input.ToLowerInvariant(), best.ToLowerInvariant()) <= 2)
        {
            if (SafeConsole.Ask($"Did you mean '{best}'?"))
            {
                return(dictionary.GetOrThrow(best));
            }
        }

        return(null);
    }
Exemplo n.º 6
0
 static float Distance(StringDistance sd, string o, string n)
 {
     return(sd.LevenshteinDistance(o, n, weight: c => c.Type == StringDistance.ChoiceType.Substitute ? 2 : 1));
 }
Exemplo n.º 7
0
 public void LevenshteinDistance()
 {
     Assert.Equal(1, d.LevenshteinDistance("hi", "ho"));
     Assert.Equal(1, d.LevenshteinDistance("hi", "hil"));
     Assert.Equal(1, d.LevenshteinDistance("hi", "h"));
 }
Exemplo n.º 8
0
        static string AskTypeReplacement(Replacements replacements, string type)
        {
            return(replacements.GetOrCreate("cleanNames").GetOrCreate(type, () =>
            {
                if (Replacements.AutoReplacement != null)
                {
                    Replacements.Selection?sel = Replacements.AutoReplacement(new Replacements.AutoReplacementContext {
                        ReplacementKey = "FixValue.Type", OldValue = type, NewValues = null
                    });

                    if (sel != null && sel.Value.NewValue != null)
                    {
                        return sel.Value.NewValue;
                    }
                }

                Console.WriteLine("Type {0} has been renamed?".FormatWith(type));

                int startingIndex = 0;
                StringDistance sd = new StringDistance();
                var list = TypeLogic.NameToType.Keys.OrderBy(t => sd.LevenshteinDistance(t, type)).ToList();
                retry:
                int maxElements = Console.LargestWindowHeight - 11;

                list.Skip(startingIndex).Take(maxElements)
                .Select((s, i) => "- {1,2}: {2} ".FormatWith(i + startingIndex == 0 ? ">" : " ", i + startingIndex, s)).ToConsole();
                Console.WriteLine();
                SafeConsole.WriteLineColor(ConsoleColor.White, "- n: None");

                int remaining = list.Count - startingIndex - maxElements;
                if (remaining > 0)
                {
                    SafeConsole.WriteLineColor(ConsoleColor.White, "- +: Show more values ({0} remaining)", remaining);
                }

                while (true)
                {
                    string answer = Console.ReadLine();

                    if (answer == null)
                    {
                        throw new InvalidOperationException("Impossible to synchronize interactively without Console");
                    }

                    answer = answer.ToLower();

                    if (answer == "+" && remaining > 0)
                    {
                        startingIndex += maxElements;
                        goto retry;
                    }

                    if (answer == "n")
                    {
                        return null;
                    }

                    if (int.TryParse(answer, out int option))
                    {
                        return list[option];
                    }

                    Console.WriteLine("Error");
                }
            }));
        }
Exemplo n.º 9
0
        // Update all string stats for which there are enough strings entered.
        private void computeStatsButton_Click(object sender, EventArgs e)
        {
            TabPage selectedTab = statsTabControl.SelectedTab;

            bool isInput1Empty = (inputTextBox1.Text == String.Empty);
            bool isInput2Empty = (inputTextBox2.Text == String.Empty);
            bool isInput3Empty = (inputTextBox3.Text == String.Empty);

            bool isInput1Error = false; //  isInput1Empty;
            bool isInput2Error = false; //  isInput2Empty && (selectedTab == tabPage2 || selectedTab == tabPage3);
            bool isInput3Error = false; //  isInput3Empty && selectedTab == tabPage3;
            bool isInputError  = isInput1Error || isInput2Error || isInput3Error;

            inputValidatorTextBox1.Text = isInput1Error ? "String #1 must be non-empty for all stats" : String.Empty;
            inputValidatorTextBox2.Text = isInput2Error
                ? "String #2 must be non-empty for 1-string and 2-string stats" : String.Empty;
            inputValidatorTextBox3.Text = isInput3Error
                ? "String #3 must be non-empty for 3-string stats" : String.Empty;

            inputValidatorTextBox1.Visible = isInput1Error;
            inputValidatorTextBox2.Visible = isInput2Error;
            inputValidatorTextBox3.Visible = isInput3Error;
            inputValidatorTextBox.Visible  = isInputError;

            if (isInputError)
            {
                int numErrors = (isInput1Error ? 1 : 0)
                                + (isInput2Error ? 1 : 0)
                                + (isInput3Error ? 1 : 0);
                inputValidatorTextBox.Text = String.Format(
                    "Please fix the {0} error{1} above before continuing.",
                    numErrors,
                    numErrors == 1 ? String.Empty : "s"
                    );
                return;
            }
            inputValidatorTextBox.Text = String.Empty;

            // One String
            stringLengthTextBox.Text = Convert.ToString(
                StringLength.Length(inputTextBox1.Text)
                );
            List <string> palindromes = Palindrome.LongestPalindromes(inputTextBox1.Text);

            longestPalindromesTextBox.Text = String.Join(Environment.NewLine, palindromes);

            // Two Strings
            levenshteinTextBox.Text = Convert.ToString(
                StringDistance.LevenshteinDistance(inputTextBox1.Text, inputTextBox2.Text)
                );
            damerauLevenshteinTextBox.Text = Convert.ToString(
                StringDistance.DamerauLevenshteinDistance(inputTextBox1.Text, inputTextBox2.Text)
                );
            optimalStringAlignmentTextBox.Text = Convert.ToString(
                StringDistance.OptimalStringAlignmentDistance(inputTextBox1.Text, inputTextBox2.Text)
                );
            longestCommonSubsequencesTextBox.Text = String.Join(Environment.NewLine,
                                                                CommonSubset.LongestCommonSubsequences(inputTextBox1.Text, inputTextBox2.Text)
                                                                );
            longestCommonSubstringsTextBox.Text = String.Join(Environment.NewLine,
                                                              CommonSubset.LongestCommonSubstrings(inputTextBox1.Text, inputTextBox2.Text)
                                                              );
        }
Exemplo n.º 10
0
    public static T?MostSimilar <T>(this IEnumerable <T> collection, Func <T, string> stringSelector, string pattern)
    {
        StringDistance sd = new StringDistance();

        return(collection.MinBy(item => sd.LevenshteinDistance(stringSelector(item), pattern)));
    }
 public void LevenshteinDistance()
 {
     Assert.True(1 == _stringDistance.LevenshteinDistance("hi", "ho"));
     Assert.True(1 == _stringDistance.LevenshteinDistance("hi", "hil"));
     Assert.True(1 == _stringDistance.LevenshteinDistance("hi", "h"));
 }