I want to find the backtracks sequence in the form of data (as it is from collatz conjecture tibble data from 1 to 10,000) at some point goes above the starting value in that sequence.
This is my output for data frame:
structure(list(start = 1:6, seq = list(1L, c(2, 1), c(3, 10,
5, 16, 8, 4, 2, 1), c(4, 2, 1), c(5, 16, 8, 4, 2, 1), c(6, 3,
10, 5, 16, 8, 4, 2, 1)), length = c(1, 2, 8, 3, 6, 9), parity = c("Odd",
"Even", "Odd", "Even", "Odd", "Even"), max_val = c(1, 2, 16,
4, 16, 16)), row.names = c(NA, -6L), class = c("tbl_df", "tbl",
"data.frame"))
This is how i did:
has_backtrack <- function(seq) {
length_seq <- length(seq)
if (length_seq < 3) {
return(FALSE)
}
for (i in 2:(length_seq - 1)) {
if (seq[i] < seq[1] && seq[i + 1] > seq[i]) {
return(TRUE)
}
}
}
However, for my current code it only shows whether a sequence increases but not above the first value.
Backtracks def: is when a sequence reaches a value that is less than the starting integer, but then increases again ABOVE the starting value/integer it can be at least once before reaching one.
I am not sure that the following is what you want. It uses R's vectorized instructions to get all points where the input sequence increases in one instruction, making the code much simpler, without
forloops.The function
has_backtrackreturns the indices to the points where the sequence increases, not the sequences values.The functions
next_collatzandcollatzare inspired in this R-bloggers code.Created on 2023-09-24 with reprex v2.0.2
Another example, with a strictly decreasing input Collatz sequence.
Created on 2023-09-24 with reprex v2.0.2
Edit
With the data set posted in the question, the Collatz sequences column is a list column and the function
has_backtrackcan belapplyed as follows.The results show that
Created on 2023-09-24 with reprex v2.0.2
And to get the values before the increase point, use
Map.Created on 2023-09-24 with reprex v2.0.2
Data
Created on 2023-09-24 with reprex v2.0.2