|
| 1 | +const std = @import("std"); |
| 2 | +const testing = std.testing; |
| 3 | + |
| 4 | +// Function that computes the minimum distance(or operations) to make 2 strings equal |
| 5 | +// Well known as the edit distance dp function. |
| 6 | +// Arguments: |
| 7 | +// word1: The first passed string |
| 8 | +// word2: The second passed string |
| 9 | +// Returns u32: The minimum operations to make the 2 strings equal |
| 10 | +pub fn minDist(comptime word1: []const u8, comptime word2: []const u8) u32 { |
| 11 | + if (word1.len == 0 and word2.len == 0) { |
| 12 | + return 0; |
| 13 | + } |
| 14 | + if (word1.len == 0 and word2.len != 0) { |
| 15 | + return @as(u32, @intCast(word2.len)); |
| 16 | + } |
| 17 | + if (word1.len != 0 and word2.len == 0) { |
| 18 | + return @as(u32, @intCast(word1.len)); |
| 19 | + } |
| 20 | + |
| 21 | + const n: usize = word1.len; |
| 22 | + const w: usize = word2.len; |
| 23 | + |
| 24 | + var dp: [n + 1][w + 1]u32 = undefined; |
| 25 | + for (0..(n + 1)) |i| { |
| 26 | + dp[i][0] = @as(u32, @intCast(i)); |
| 27 | + } |
| 28 | + |
| 29 | + for (0..(w + 1)) |i| { |
| 30 | + dp[0][i] = @as(u32, @intCast(i)); |
| 31 | + } |
| 32 | + |
| 33 | + for (1..(n + 1)) |i| { |
| 34 | + for (1..(w + 1)) |j| { |
| 35 | + if (word1[i - 1] == word2[j - 1]) { |
| 36 | + dp[i][j] = dp[i - 1][j - 1]; |
| 37 | + } else { |
| 38 | + dp[i][j] = @min(dp[i - 1][j - 1], @min(dp[i - 1][j], dp[i][j - 1])) + 1; |
| 39 | + } |
| 40 | + } |
| 41 | + } |
| 42 | + |
| 43 | + return dp[n][w]; |
| 44 | +} |
| 45 | + |
| 46 | +test "Testing edit distance function" { |
| 47 | + const word1 = "hello"; |
| 48 | + const word2 = "world"; |
| 49 | + |
| 50 | + try testing.expect(minDist(word1, word2) == 4); |
| 51 | + |
| 52 | + const word3 = "Hell0There"; |
| 53 | + const word4 = "hellothere"; |
| 54 | + |
| 55 | + try testing.expect(minDist(word3, word4) == 3); |
| 56 | + |
| 57 | + const word5 = "abcdefg"; |
| 58 | + const word6 = "abcdefg"; |
| 59 | + |
| 60 | + try testing.expect(minDist(word5, word6) == 0); |
| 61 | + |
| 62 | + const word7 = ""; |
| 63 | + const word8 = "abasda"; |
| 64 | + |
| 65 | + try testing.expect(minDist(word7, word8) == 6); |
| 66 | + |
| 67 | + const word9 = "abcsa"; |
| 68 | + const word10 = ""; |
| 69 | + |
| 70 | + try testing.expect(minDist(word9, word10) == 5); |
| 71 | + |
| 72 | + const word11 = "sdasdafda"; |
| 73 | + const word12 = "sdasdbbba"; |
| 74 | + |
| 75 | + try testing.expect(minDist(word11, word12) == 3); |
| 76 | +} |
0 commit comments