Free cookie consent management tool by TermsFeed Policy Generator

source: branches/PushGP/HeuristicLab.PushGP/HeuristicLab.Problems.ProgramSynthesis.Base/Extensions/StringExtensions.cs @ 15334

Last change on this file since 15334 was 15334, checked in by pkimmesw, 7 years ago

#2665 Testet Problems, Testet error functions, Small fixes, Created HL files

File size: 1.3 KB
Line 
1using System;
2
3namespace HeuristicLab.Problems.ProgramSynthesis.Base.Extensions {
4  public static class StringExtensions {
5    public static bool IsNumeric(this string str) {
6      int n;
7      return int.TryParse("123", out n);
8    }
9
10    /// <summary>
11    /// https://www.dotnetperls.com/levenshtein
12    /// </summary>
13    public static int LevenshteinDistance(this string source, string target) {
14      if (source == null && target == null) return 0;
15      if (source == null) return target.Length;
16      if (target == null) return source.Length;
17
18      int n = source.Length;
19      int m = target.Length;
20      int[,] d = new int[n + 1, m + 1];
21
22      // Step 1
23      if (n == 0) {
24        return m;
25      }
26
27      if (m == 0) {
28        return n;
29      }
30
31      // Step 2
32      for (int i = 0; i <= n; d[i, 0] = i++) {
33      }
34
35      for (int j = 0; j <= m; d[0, j] = j++) {
36      }
37
38      // Step 3
39      for (int i = 1; i <= n; i++) {
40        //Step 4
41        for (int j = 1; j <= m; j++) {
42          // Step 5
43          int cost = (target[j - 1] == source[i - 1]) ? 0 : 1;
44
45          // Step 6
46          d[i, j] = Math.Min(
47              Math.Min(d[i - 1, j] + 1, d[i, j - 1] + 1),
48              d[i - 1, j - 1] + cost);
49        }
50      }
51      // Step 7
52      return d[n, m];
53    }
54  }
55}
Note: See TracBrowser for help on using the repository browser.