The longest common subsequence algorithm implemented by Ruby _ruby Special topic

Source: Internet
Author: User
Tags arrays rand

Longest public subsequence, LCS, dynamic programming implementation.

#encoding: Utf-8 #author: Xu Jin, 4100213 #date: Nov, #Longest-commom-subsequence #to find a longest commom subse Quence 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 b chars = (" A ".." E "). To_a x, y = [], [] 1.upto (rand (5) + 5) {|i| x << Chars[rand (chars.size-1)]} 1.upto (rand (5) + 5) {|i| y <&l T Chars[rand (chars.size-1)]} printf ("The random character arrays are:%s and%s\n", X, y) c = array.new (X.size + 1) {ARRAY.N
   EW (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) does for J-(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 def Prin T_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) end lcs_length (x, y, C, b)
 Print "The longest-commom-subsequence is:" Print_lcs (x, B, X.size, y.size)

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.