Advertisement
Guest User

Untitled

a guest
Aug 14th, 2018
73
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
OCaml 1.77 KB | None | 0 0
  1. open Js.String
  2.  
  3. module Ops = struct
  4.   type t =
  5.     | Delete of string * int
  6.     | Insert of string * string * int
  7.     | Replace of string * string * int
  8.  
  9.   let run op = match op with
  10.     | Delete (str, i) ->
  11.       (slice ~from:0 ~to_:i str) ^ (sliceToEnd ~from:(i + 1) str)
  12.     | Insert (str, char, i) ->
  13.       if i = 0 then char ^ str
  14.       else if i = length str - 1 then str ^ char
  15.       else (slice ~from:0 ~to_:i str) ^ char ^ (sliceToEnd ~from:i str)
  16.     | Replace (str, char, i) ->
  17.       (slice ~from:0 ~to_:i str) ^ char ^ (sliceToEnd ~from:(i + 1) str)
  18. end
  19.  
  20. let max_safe_int = [%raw "Number.MAX_SAFE_INTEGER"]
  21.  
  22. let mem f = fun w1 w2 p1 ->
  23.   let dict = Js.Dict.empty () in
  24.   match Js.Dict.get dict w1 with
  25.   | None ->
  26.     let result = f w1 w2 p1 in
  27.     Js.Dict.set dict w1 result;
  28.     result
  29.   | Some num -> num
  30.  
  31. let rec edit_distance w1 w2 idx =
  32.   let len1, len2 = length w1, length w2 in
  33.   if w1 = w2
  34.     then 0
  35.   else if idx = length w1
  36.     then max_safe_int
  37.   else
  38.     let (c1, c2) = (get w1 idx, get w2 idx) in
  39.     if c1 = c2 then edit_distance w1 w2 (idx + 1)
  40.     else
  41.       let open Ops in
  42.       let replace =
  43.         edit_distance (run (Replace (w1, c2, idx))) w2 (idx + 1)
  44.       in
  45.  
  46.       if len1 > len2 then
  47.         let delete =
  48.           edit_distance (run (Delete (w1, idx))) w2 (idx - 1)
  49.         in
  50.         1 + if idx = len2
  51.           then delete
  52.         else
  53.           Js.Math.min_int replace delete
  54.       else if len1 < len2 then
  55.         let insert =
  56.           edit_distance (run (Insert (w1, c2, idx))) w2 (idx + 1)
  57.         in
  58.         1 + if idx = len2
  59.           then insert
  60.         else
  61.           Js.Math.min_int replace insert
  62.       else
  63.         1 + replace
  64.      
  65. let minDistance w1 w2 = (mem edit_distance) w1 w2 0
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement