motzkin_triangle.sf 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. #!/usr/bin/ruby
  2. # Daniel "Trizen" Șuteu
  3. # Date: 23 February 2018
  4. # https://github.com/trizen
  5. # Simple generation of the Motzkin triangle.
  6. # See also:
  7. # https://oeis.org/A026300 (Motzkin triangle)
  8. # https://oeis.org/A005773 (sum of rows)
  9. # https://oeis.org/A129703 (sum of rows + 1)
  10. # For n>0, A129703(n)-1 is the sum of the n-th row of Motzkin's triangle.
  11. func motzkin_triangle(num, callback) {
  12. var row = []
  13. { |n|
  14. row = [0, 1, {|i| row[i+2] + row[i] + row[i+1] }.map(0 .. n-3)..., 0]
  15. callback(row.grep{ .> 0 })
  16. } << 2..(num+1)
  17. }
  18. motzkin_triangle(12, {|row|
  19. row.map { "%4s" % _ }.join(' ').say
  20. })
  21. say "\n=> Sum of the rows of Motzkin's triangle:"
  22. say gather {
  23. motzkin_triangle(15, {|row| take(row.sum) })
  24. }
  25. func motzkin_row_sum(n) {
  26. sum(0 .. n, {|k|
  27. sum(0 .. floor(k/2), {|t|
  28. binomial(n, 2*t + n - k) * (binomial(2*t + n - k, t) - binomial(2*t + n - k, t-1))
  29. })
  30. })
  31. }
  32. say 15.of(motzkin_row_sum)
  33. __END__
  34. 1
  35. 1 1
  36. 1 2 2
  37. 1 3 5 4
  38. 1 4 9 12 9
  39. 1 5 14 25 30 21
  40. 1 6 20 44 69 76 51
  41. 1 7 27 70 133 189 196 127
  42. 1 8 35 104 230 392 518 512 323
  43. 1 9 44 147 369 726 1140 1422 1353 835
  44. 1 10 54 200 560 1242 2235 3288 3915 3610 2188
  45. 1 11 65 264 814 2002 4037 6765 9438 10813 9713 5798
  46. => Sum of the rows of Motzkin's triangle:
  47. [1, 2, 5, 13, 35, 96, 267, 750, 2123, 6046, 17303, 49721, 143365, 414584, 1201917]
  48. [1, 2, 5, 13, 35, 96, 267, 750, 2123, 6046, 17303, 49721, 143365, 414584, 1201917]