recaman_s_sequence.sf 1.1 KB

12345678910111213141516171819202122232425262728293031323334353637383940
  1. #!/usr/bin/ruby
  2. # Generate the first n terms of the Recamán's sequence.
  3. # The Recamán's sequence is defined as:
  4. # a(0) = 0
  5. # a(n) = a(n-1) - n, if positive and not already in the sequence,
  6. # a(n) = a(n-1) + n, otherwise
  7. # OEIS sequence:
  8. # https://oeis.org/A005132
  9. func recamán_sequence_first(n) {
  10. var a = [0]
  11. var s = Hash()
  12. for k in (1 ..^ n) {
  13. var t1 = a[k-1]-k
  14. var t2 = a[k-1]+k
  15. if ((t1 > 0) && !s.has(t1)) {
  16. a[k] = t1
  17. s{t1} = true
  18. }
  19. else {
  20. a[k] = t2
  21. s{t2} = true
  22. }
  23. }
  24. return a
  25. }
  26. say recamán_sequence_first(100)
  27. __END__
  28. [0, 1, 3, 6, 2, 7, 13, 20, 12, 21, 11, 22, 10, 23, 9, 24, 8, 25, 43, 62, 42, 63, 41, 18, 42, 17, 43, 16, 44, 15, 45, 14, 46, 79, 113, 78, 114, 77, 39, 78, 38, 79, 37, 80, 36, 81, 35, 82, 34, 83, 33, 84, 32, 85, 31, 86, 30, 87, 29, 88, 28, 89, 27, 90, 26, 91, 157, 224, 156, 225, 155, 226, 154, 227, 153, 228, 152, 75, 153, 74, 154, 73, 155, 72, 156, 71, 157, 70, 158, 69, 159, 68, 160, 67, 161, 66, 162, 65, 163, 64]