Advertisement
Guest User

Untitled

a guest
Mar 19th, 2021
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.71 KB | None | 0 0
  1. const std = @import("std");
  2.  
  3. pub fn main() void {
  4. const start = "hello";
  5. const end = "hal";
  6.  
  7. const dist: u8 = edit_distance(start, end);
  8. std.debug.print("The minimum edit distance between {s} and {s} is {}\n", .{start, end, dist});
  9. }
  10.  
  11. fn edit_distance(comptime start: []const u8, comptime end: []const u8) u8 {
  12. // Figure out why x and y are switched here.
  13. const x_dim = start.len + 1;
  14. const y_dim = end.len + 1;
  15. var matrix: [y_dim][x_dim]u8 = .{.{0} ** x_dim} ** y_dim;
  16.  
  17. var n: u8 = 0;
  18. while (n < x_dim) : (n += 1) {
  19. matrix[0][n] = n;
  20. }
  21.  
  22. n = 0;
  23. while (n < y_dim) : (n += 1) {
  24. matrix[n][0] = n;
  25. }
  26.  
  27. var i: u8 = 1;
  28. while (i < x_dim): (i += 1) {
  29. const letter_i = start[i-1];
  30. var j: u8 = 1;
  31. while (j < y_dim): (j += 1) {
  32. const letter_j = end[j-1];
  33. if (letter_i == letter_j) {
  34. matrix[j][i] = matrix[j-1][i-1];
  35. }
  36. else {
  37. const delete: u8 = matrix[j][i-1] + 1;
  38. const insert: u8 = matrix[j-1][i] + 1;
  39. const substitute: u8 = matrix[j-1][i-1] + 1;
  40. var minimum: u8 = delete;
  41. if (insert < minimum) {
  42. minimum = insert;
  43. }
  44. if (substitute < minimum) {
  45. minimum = substitute;
  46. }
  47. matrix[j][i] = minimum;
  48. }
  49. }
  50. }
  51.  
  52. for (matrix) |row, row_index| {
  53. for (row) |cell, column_index| {
  54. std.debug.print("{} ", .{cell});
  55. }
  56. std.debug.print("\n", .{});
  57. }
  58.  
  59. return matrix[y_dim-1][x_dim-1];
  60. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement