fork(1) download
  1. #!/usr/bin/ruby
  2.  
  3. class An
  4.  
  5. def initialize(k = 1, t = 10)
  6. @k = k
  7. @t = t
  8. @mem = Hash.new
  9. end
  10.  
  11. def a(k, n)
  12.  
  13. # Recall from memory.
  14. key = "#{k},#{n}"
  15. return @mem[key] unless @mem[key] == nil
  16.  
  17. # Otherwise compute and remember.
  18. return (@mem[key] = 1) if (k == 0) and (n == 0)
  19. return (@mem[key] = 0) if (k < 0) or (n < 0)
  20. @mem[key] = a(k-1, n) + a(k-1, n-1) + a(k-1, n-2) + a(k-1, n-3)
  21. end
  22.  
  23. def terms
  24. (0 .. @t).map { |n| a(@k, n) }
  25. end
  26.  
  27. def print
  28. puts terms().join(',')
  29. end
  30. end
  31.  
  32. # Print the initial ten terms of the first few sequences.
  33. (0 .. 15).each do |k|
  34. print "k = #{k}: "
  35. An.new(k, 10).print
  36. end
Success #stdin #stdout 0.03s 7460KB
stdin
Standard input is empty
stdout
k = 0: 1,0,0,0,0,0,0,0,0,0,0
k = 1: 1,1,1,1,0,0,0,0,0,0,0
k = 2: 1,2,3,4,3,2,1,0,0,0,0
k = 3: 1,3,6,10,12,12,10,6,3,1,0
k = 4: 1,4,10,20,31,40,44,40,31,20,10
k = 5: 1,5,15,35,65,101,135,155,155,135,101
k = 6: 1,6,21,56,120,216,336,456,546,580,546
k = 7: 1,7,28,84,203,413,728,1128,1554,1918,2128
k = 8: 1,8,36,120,322,728,1428,2472,3823,5328,6728
k = 9: 1,9,45,165,486,1206,2598,4950,8451,13051,18351
k = 10: 1,10,55,220,705,1902,4455,9240,17205,29050,44803
k = 11: 1,11,66,286,990,2882,7282,16302,32802,59950,100298
k = 12: 1,12,78,364,1353,4224,11440,27456,59268,116336,209352
k = 13: 1,13,91,455,1807,6019,17381,44473,102388,214500,412412
k = 14: 1,14,105,560,2366,8372,25662,69680,170261,378742,773773
k = 15: 1,15,120,680,3045,11403,36960,106080,273975,644345,1392456