Ruby实现的最长公共子序列算法
技术  /  管理员 发布于 5年前   440
最长公共子序列,LCS,动态规划实现。
#encoding: utf-8#author: xu jin, 4100213#date: Nov 01, 2012#Longest-Commom-Subsequence#to find a longest commom subsequence of two given character arrays by using LCS algorithm#example output:#The random character arrays are: ["b", "a", "c", "a", "a", "b", "d"] and ["a", "c", "a", "c", "a", "a", "b"]#The Longest-Commom-Subsequence is: a c a a bchars = ("a".."e").to_ax, y = [], []1.upto(rand(5) + 5) { |i| x << chars[rand(chars.size-1)] }1.upto(rand(5) + 5) { |i| y << chars[rand(chars.size-1)] }printf("The random character arrays are: %s and %s\n", x, y)c = Array.new(x.size + 1){Array.new(y.size + 1)}b = Array.new(x.size + 1){Array.new(y.size + 1)}def LCS_length(x, y ,c ,b) m, n = x.size, y.size (0..m).each{|i| c[i][0] = 0} (0..n).each{|j| c[0][j] = 0} for i in (1..m) do for j in(1..n) do if(x[i - 1] == y [j - 1]) c[i][j] = c[i - 1][j - 1] + 1; b[i][j] = 0 else if(c[i - 1][j] >= c[i][j - 1]) c[i][j] = c[i - 1][j] b[i][j] = 1 else c[i][j] = c[i][j - 1] b[i][j] = 2 end end end endenddef Print_LCS(x, b, i, j) return if(i == 0 || j == 0) if(b[i][j] == 0) Print_LCS(x, b, i-1, j-1) printf("%c ", x[i - 1]) elsif(b[i][j] == 1) Print_LCS(x, b, i-1, j) else Print_LCS(x, b, i, j-1) endendLCS_length(x, y, c ,b) print "The Longest-Commom-Subsequence is: "Print_LCS(x, b, x.size, y.size)
122 在
学历:一种延缓就业设计,生活需求下的权衡之选中评论 工作几年后,报名考研了,到现在还没认真学习备考,迷茫中。作为一名北漂互联网打工人..123 在
Clash for Windows作者删库跑路了,github已404中评论 按理说只要你在国内,所有的流量进出都在监控范围内,不管你怎么隐藏也没用,想搞你分..原梓番博客 在
在Laravel框架中使用模型Model分表最简单的方法中评论 好久好久都没看友情链接申请了,今天刚看,已经添加。..博主 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 @1111老铁这个不行了,可以看看近期评论的其他文章..1111 在
佛跳墙vpn软件不会用?上不了网?佛跳墙vpn常见问题以及解决办法中评论 网站不能打开,博主百忙中能否发个APP下载链接,佛跳墙或极光..
Copyright·© 2019 侯体宗版权所有·
粤ICP备20027696号