lis_dynamic_programming.sf 526 B

1234567891011121314151617181920212223242526272829
  1. #!/usr/bin/ruby
  2. #
  3. ## https://rosettacode.org/wiki/Longest_increasing_subsequence
  4. #
  5. func lis(a) {
  6. var l = a.len.of { [] }
  7. l[0] << a[0]
  8. 1.to(a.len-1).each { |i|
  9. i.range.each { |j|
  10. if ((a[j] < a[i]) && (l[i].len < l[j].len+1)) {
  11. l[i] = [l[j]...]
  12. }
  13. }
  14. l[i] << a[i]
  15. }
  16. l.max_by { .len }
  17. }
  18. var a = lis(%i<3 2 6 4 5 1>)
  19. var b = lis(%i<0 8 4 12 2 10 6 14 1 9 5 13 3 11 7 15>)
  20. say a
  21. say b
  22. assert_eq(a, [2, 4, 5])
  23. assert_eq(b, [0, 2, 6, 9, 11, 15])