longest_common_subsequence.sf 783 B

1234567891011121314151617181920212223242526272829303132
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Longest_common_subsequence#Sidef
  4. #
  5. #
  6. ## This is generalized version which works with strings
  7. ## but also with arrays of any kind, such as arrays of characters.
  8. #
  9. func lcs(xstr, ystr) is cached {
  10. xstr.is_empty && return xstr;
  11. ystr.is_empty && return ystr;
  12. var(x, xs, y, ys) = (xstr.slice(0,1), xstr.slice(1),
  13. ystr.slice(0,1), ystr.slice(1));
  14. if (x == y) {
  15. x + lcs($xs, $ys)
  16. } else {
  17. [lcs(xstr, ys), lcs(xs, ystr)].max_by { .len };
  18. }
  19. }
  20. say lcs("thisisatest", "testing123testing")
  21. say lcs(%g"thisisatest", %g"testing123testing")
  22. assert_eq(lcs("thisisatest", "testing123testing"), "tsitest")
  23. assert_eq(lcs(%g"thisisatest", %g"testing123testing"), "tsitest".chars)