'Sequence with stopping values
This is like a regular tribonacci sequence, however, I want the sequence to stop whenever the term is at the min or max value.
This is what I have started
sequence <- function(a1=0, a2=0, a3=1, min=0, max=30) {
an <- c()
a[1] <- a1
a[2] <- a2
a[3] <- a3
while(a <= max || a >= min) {
a[i] <- a[i-1] + a[i-2] + a[i-3]
an <- c(an, a[i])
}
an
}
Are there any suggestions regarding my code setup, and how to fix the indexing?
Solution 1:[1]
Here is a way of coding this using abs()
:
tribonacci <- function(start=c(0, 0, 1), maxval=15) {
a <- start
i <- 3
while(abs(a[i]) <= maxval) {
i <- i + 1
a[i] <- a[i-3] + a[i-2] + a[i-1]
}
a[1:(i-1)]
}
tribonacci(maxval=24)
# [1] 0 0 1 1 2 4 7 13 24
tribonacci(start=c(0, 1, -3), maxval=30)
# [1] 0 1 -3 -2 -4 -9 -15 -28
Since we use the absolute value, we just need one argument to specify the maximum/minimum.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 |