-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathrecaman_s_sequence.sf
39 lines (28 loc) · 1.05 KB
/
recaman_s_sequence.sf
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
#!/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]