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

复制代码 代码如下:
#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])"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,最短编辑距离,算法

免责声明:本站文章均来自网站采集或用户投稿,网站不提供任何软件下载或自行开发的软件! 如有用户或公司发现本站内容信息存在侵权行为,请邮件告知! 858582#qq.com
内蒙古资源网 Copyright www.nmgbbs.com

评论“Ruby实现的最短编辑距离计算方法”

暂无“Ruby实现的最短编辑距离计算方法”评论...

RTX 5090要首发 性能要翻倍!三星展示GDDR7显存

三星在GTC上展示了专为下一代游戏GPU设计的GDDR7内存。

首次推出的GDDR7内存模块密度为16GB,每个模块容量为2GB。其速度预设为32 Gbps(PAM3),但也可以降至28 Gbps,以提高产量和初始阶段的整体性能和成本效益。

据三星表示,GDDR7内存的能效将提高20%,同时工作电压仅为1.1V,低于标准的1.2V。通过采用更新的封装材料和优化的电路设计,使得在高速运行时的发热量降低,GDDR7的热阻比GDDR6降低了70%。