From a87a1476ad537bd86b1a27ed9950c96b6d3dc127 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=C8=98tefan-Iulian=20Alecu?= <165364995+pascalecu@users.noreply.github.com> Date: Wed, 13 May 2026 22:38:18 +0300 Subject: [PATCH] Add Longest Common Subsequence in Ruby --- archive/r/ruby/longest-common-subsequence.rb | 56 ++++++++++++++++++++ 1 file changed, 56 insertions(+) create mode 100644 archive/r/ruby/longest-common-subsequence.rb diff --git a/archive/r/ruby/longest-common-subsequence.rb b/archive/r/ruby/longest-common-subsequence.rb new file mode 100644 index 000000000..91f0ea4bd --- /dev/null +++ b/archive/r/ruby/longest-common-subsequence.rb @@ -0,0 +1,56 @@ +# frozen_string_literal: true + +USAGE = 'Usage: please provide two lists in the format "1, 2, 3, 4, 5"' + +def usage! + warn USAGE + exit 1 +end + +def parse_list(str) + str.split(",").map { Integer(it.strip) } +rescue ArgumentError, NoMethodError + usage! +end + +def lcs(a, b) + n = a.size + m = b.size + + dp = Array.new(n + 1) { Array.new(m + 1, 0) } + + (1..n).each do |i| + (1..m).each do |j| + dp[i][j] = if a[i - 1] == b[j - 1] + dp[i - 1][j - 1] + 1 + else + [dp[i - 1][j], dp[i][j - 1]].max + end + end + end + + i, j = n, m + result = [] + + while i > 0 && j > 0 + if a[i - 1] == b[j - 1] + result << a[i - 1] + i -= 1 + j -= 1 + elsif dp[i - 1][j] >= dp[i][j - 1] + i -= 1 + else + j -= 1 + end + end + + result.reverse +end + +a_str, b_str = ARGV +usage! if a_str.nil? || b_str.nil? || a_str.strip.empty? || b_str.strip.empty? + +a = parse_list(a_str) +b = parse_list(b_str) + +puts lcs(a, b).join(", ")