欢迎来到代码驿站!

Ruby

当前位置:首页 > 脚本语言 > Ruby

Ruby实现的最短编辑距离计算方法

时间:2021-02-10 14:51:27|栏目:Ruby|点击:

利用动态规划算法,实现最短编辑距离的计算。

复制代码 代码如下:

#encoding: utf-8
#author: xu jin
#date: Nov 12, 2012
#EditDistance
#to find the minimum cost by using EditDistance algorithm
#example output:
#  "Please input a string: "
#  exponential
#  "Please input the other string: "
#  polynomial
#  "The expected cost is 6"
#  The result is :
#    ["e", "x", "p", "o", "n", "e", "n", "-", "t", "i", "a", "l"]
#    ["-", "-", "p", "o", "l", "y", "n", "o", "m", "i", "a", "l"]

p "Please input a string: "
x = gets.chop.chars.map{|c| c}
p "Please input the other string: "
y = gets.chop.chars.map{|c| c}
x.unshift(" ")
y.unshift(" ")
e = Array.new(x.size){Array.new(y.size)}
flag = Array.new(x.size){Array.new(y.size)}
DEL, INS, CHA, FIT = (1..4).to_a  #deleat, insert, change, and fit
 
def edit_distance(x, y, e, flag)
  (0..x.length - 1).each{|i| e[i][0] = i}
  (0..y.length - 1).each{|j| e[0][j] = j}
  diff = Array.new(x.size){Array.new(y.size)}
  for i in(1..x.length - 1) do
    for j in(1..y.length - 1) do
      diff[i][j] = (x[i] == y[j])? 0: 1
      e[i][j] = [e[i-1][j] + 1, e[i][j - 1] + 1, e[i-1][j - 1] + diff[i][j]].min
      if e[i][j] == e[i-1][j] + 1
        flag[i][j] = DEL
      elsif e[i][j] == e[i-1][j - 1] + 1
        flag[i][j] = CHA
      elsif e[i][j] == e[i][j - 1] + 1
        flag[i][j] = INS      
      else flag[i][j] = FIT
      end    
    end
  end 
end

out_x, out_y = [], []

def solution_structure(x, y, flag, i, j, out_x, out_y)
  case flag[i][j]
  when FIT
    out_x.unshift(x[i])
    out_y.unshift(y[j]) 
    solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)
  when DEL
    out_x.unshift(x[i])
    out_y.unshift('-')
    solution_structure(x, y, flag, i - 1, j, out_x, out_y)
  when INS
    out_x.unshift('-')
    out_y.unshift(y[j])
    solution_structure(x, y, flag, i, j - 1, out_x, out_y)
  when CHA
    out_x.unshift(x[i])
    out_y.unshift(y[j])
    solution_structure(x, y, flag, i - 1, j - 1, out_x, out_y)
  end
  #if flag[i][j] == nil ,go here
  return if i == 0 && j == 0   
  if j == 0
      out_y.unshift('-')
      out_x.unshift(x[i])
      solution_structure(x, y, flag, i - 1, j, out_x, out_y)
  elsif i == 0
      out_x.unshift('-')
      out_y.unshift(y[j])
      solution_structure(x, y, flag, i, j - 1, out_x, out_y)
  end
end

edit_distance(x, y, e, flag)
p "The expected edit distance is #{e[x.length - 1][y.length - 1]}"
solution_structure(x, y, flag, x.length - 1, y.length - 1, out_x, out_y)
puts "The result is : \n  #{out_x}\n  #{out_y}"


上一篇:ruby 正则表达式详解及示例代码

栏    目:Ruby

下一篇:简要解读Ruby面向对象编程中的作用域

本文标题:Ruby实现的最短编辑距离计算方法

本文地址:http://www.codeinn.net/misctech/60552.html

推荐教程

广告投放 | 联系我们 | 版权申明

重要申明:本站所有的文章、图片、评论等,均由网友发表或上传并维护或收集自网络,属个人行为,与本站立场无关。

如果侵犯了您的权利,请与我们联系,我们将在24小时内进行处理、任何非本站因素导致的法律后果,本站均不负任何责任。

联系QQ:914707363 | 邮箱:codeinn#126.com(#换成@)

Copyright © 2020 代码驿站 版权所有