12345678910111213141516171819202122232425262728293031323334353637383940 |
- #!/usr/bin/ruby
- # Generate the first n terms of the Recamán's sequence.
- # The Recamán's sequence is defined as:
- # a(0) = 0
- # a(n) = a(n-1) - n, if positive and not already in the sequence,
- # a(n) = a(n-1) + n, otherwise
- # OEIS sequence:
- # https://oeis.org/A005132
- func recamán_sequence_first(n) {
- var a = [0]
- var s = Hash()
- for k in (1 ..^ n) {
- var t1 = a[k-1]-k
- var t2 = a[k-1]+k
- if ((t1 > 0) && !s.has(t1)) {
- a[k] = t1
- s{t1} = true
- }
- else {
- a[k] = t2
- s{t2} = true
- }
- }
- return a
- }
- say recamán_sequence_first(100)
- __END__
- [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]
|