|
| 1 | +using System.Runtime.CompilerServices; |
| 2 | + |
| 3 | +var runMs = int.Parse(args[0]); |
| 4 | +var warmupMs = int.Parse(args[1]); |
| 5 | +var inputPath = args[2]; |
| 6 | + |
| 7 | +var content = File.ReadAllLines(inputPath); |
| 8 | + |
| 9 | +Benchmark<List<int>>.Run(() => Levenshtein(content), warmupMs); |
| 10 | + |
| 11 | +var result = Benchmark<List<int>>.Run(() => Levenshtein(content), runMs); |
| 12 | + |
| 13 | +var summedResult = new BenchmarkResult<int>( |
| 14 | + result!.MeanMs, |
| 15 | + result.StdDevMs, |
| 16 | + result.MinMs, |
| 17 | + result.MaxMs, |
| 18 | + result.Runs, |
| 19 | + result.Result.Sum()); |
| 20 | + |
| 21 | +Console.WriteLine(summedResult); |
| 22 | + |
| 23 | +return; |
| 24 | + |
| 25 | +static List<int> Levenshtein(string[] content) |
| 26 | +{ |
| 27 | + var distances = new List<int>(); |
| 28 | + |
| 29 | + for (var i = 0; i < content.Length; i++) |
| 30 | + { |
| 31 | + for (var j = i + 1; j < content.Length; j++) |
| 32 | + { |
| 33 | + distances.Add(LevenshteinDistance(content[i], content[j])); |
| 34 | + } |
| 35 | + } |
| 36 | + |
| 37 | + return distances; |
| 38 | +} |
| 39 | + |
| 40 | +[MethodImpl(MethodImplOptions.AggressiveOptimization)] |
| 41 | +static int LevenshteinDistance(ReadOnlySpan<char> str1, ReadOnlySpan<char> str2) |
| 42 | +{ |
| 43 | + // Early termination checks |
| 44 | + if (str1.SequenceEqual(str2)) |
| 45 | + { |
| 46 | + return 0; |
| 47 | + } |
| 48 | + |
| 49 | + if (str1.IsEmpty) |
| 50 | + { |
| 51 | + return str2.Length; |
| 52 | + } |
| 53 | + |
| 54 | + if (str2.IsEmpty) |
| 55 | + { |
| 56 | + return str1.Length; |
| 57 | + } |
| 58 | + |
| 59 | + // Ensure str1 is the shorter string |
| 60 | + if (str1.Length > str2.Length) |
| 61 | + { |
| 62 | + var strtemp = str2; |
| 63 | + str2 = str1; |
| 64 | + str1 = strtemp; |
| 65 | + } |
| 66 | + |
| 67 | + // Create two rows, previous and current |
| 68 | + Span<int> prev = stackalloc int[str1.Length + 1]; |
| 69 | + Span<int> curr = stackalloc int[str1.Length + 1]; |
| 70 | + |
| 71 | + // initialize the previous row |
| 72 | + for (var i = 0; i <= str1.Length; i++) |
| 73 | + { |
| 74 | + prev[i] = i; |
| 75 | + } |
| 76 | + |
| 77 | + // Iterate and compute distance |
| 78 | + for (var i = 1; i <= str2.Length; i++) |
| 79 | + { |
| 80 | + curr[0] = i; |
| 81 | + for (var j = 1; j <= str1.Length; j++) |
| 82 | + { |
| 83 | + var cost = (str1[j - 1] == str2[i - 1]) ? 0 : 1; |
| 84 | + curr[j] = Math.Min( |
| 85 | + prev[j] + 1, // Deletion |
| 86 | + Math.Min(curr[j - 1] + 1, // Insertion |
| 87 | + prev[j - 1] + cost) // Substitution |
| 88 | + ); |
| 89 | + } |
| 90 | + |
| 91 | + // Swap spans |
| 92 | + var temp = prev; |
| 93 | + prev = curr; |
| 94 | + curr = temp; |
| 95 | + } |
| 96 | + |
| 97 | + // Return final distance, stored in prev[m] |
| 98 | + return prev[str1.Length]; |
| 99 | +} |
0 commit comments