Ruby Implementation of Longest Common subsequences

Source: Internet
Author: User

Longest Common subsequence, LCs, dynamic planning implementation.

# Encoding: UTF-8 # Author: Xu Jin, 4100213 # Date: nov 01,201 2 # 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 bchars = ("".. "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 enddef 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)
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.