Let's say I have the following vector:
vec = c(29, 30, 15, 29, 17, 25, 24, 28, 25, 24, 28, 25, 24, 28, 25, 24, 28)
You'll notice there are three repeating elements (25, 24, and 28). How can I get R to recognize when there are repeating elements (or cycles) in a vector? I want to detect this no matter how many elements are repeating (2 or 5 rather than 3) and no matter how many elements into the vector it starts.
For context, I've got an algorithm that is trying to converge on a value, but sometimes it gets stuck in this repeating loop. I want R to detect when it's stuck in this infinite loop and get out. The vec
in my example is a log of the value at each iteration.
I've figured out how I can catch double repeating elements (saving the value from the last iteration to compare to the current iteration) but this 3+ repeating elements has me puzzled.
This function will look for patterns of 2 repeated. I calculate a hash of pairs of element [i] with [i+1] by multiplying the second one by "100" and adding to the first one. You can change this factor to some other number, assuming your integers are bounded by that factor. You might want to change this to 1000000. If you have large integers, you may want to rethink this.
Then I look to make sure the hashes are all unique, i.e. the transition from [i] to [i+1] only happens once.
Here's my test