Skip to content

Instantly share code, notes, and snippets.

@primaryobjects
Last active June 15, 2018 02:53
Show Gist options
  • Save primaryobjects/c829ebe5152efb7d6e228482a982c486 to your computer and use it in GitHub Desktop.
Save primaryobjects/c829ebe5152efb7d6e228482a982c486 to your computer and use it in GitHub Desktop.
recaman <- function(n, s=c()) {
a <- 0
if (n > 0) {
val <- recaman(n - 1, s)
a <- val$a
s <- c(val$s, a)
an1 <- a - n
if (an1 > -1 && !(an1 %in% s)) {
# If not in sequence.
a <- an1
}
else {
# If in sequence.
a <- a + n
}
}
list(a=a, s=c(s, a))
}
for (i in 1:100) print(recaman(i)$a)
# Visualization
library(ggplot2)
data <- as.data.frame(sapply(1:100, function(a) { recaman(a)$a }))
names(data) <- c('y')
data$x <- as.numeric(row.names(data))
g <- ggplot(data, aes(x=x, y=y, color=y))
g <- g + geom_point(size=2, shape=16)
g <- g + labs(title='Recman Sequence', x='Sequence #', y='Value')
g <- g + scale_color_gradient(low='purple', high='pink')
g <- g + theme(legend.position="none")
g <- g + scale_x_continuous(breaks=c(seq(from=1, to=nrow(data), by=nrow(data)/20), nrow(data)))
g
a
1 1
2 3
3 6
4 2
5 7
6 13
7 20
8 12
9 21
10 11
11 22
12 10
13 23
14 9
15 24
16 8
17 25
18 43
19 62
20 42
21 63
22 41
23 18
24 42
25 17
26 43
27 16
28 44
29 15
30 45
31 14
32 46
33 79
34 113
35 78
36 114
37 77
38 39
39 78
40 38
41 79
42 37
43 80
44 36
45 81
46 35
47 82
48 34
49 83
50 33
51 84
52 32
53 85
54 31
55 86
56 30
57 87
58 29
59 88
60 28
61 89
62 27
63 90
64 26
65 91
66 157
67 224
68 156
69 225
70 155
71 226
72 154
73 227
74 153
75 228
76 152
77 75
78 153
79 74
80 154
81 73
82 155
83 72
84 156
85 71
86 157
87 70
88 158
89 69
90 159
91 68
92 160
93 67
94 161
95 66
96 162
97 65
98 163
99 64
100 164
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment