Say I have the vector { 1, 1, 2, 1, 1, 2 }, I want to find out the largest frequency of a period at the end of the vector. In this case, the frequency (curl) is 2, since 112 is repeated twice. And since any period that is repeated at least twice is at most half the vector length, I only need to scan through half the vector.
I am looking for the fastest way to compare parts of the same vector. On recent suggestion, I went over to use std::equal(), but I don't know whether this is the best function or if I used it in the fastest possible way.
This is my function currently:
vector<int> sequence = someVec;
int curl = 1;
for (int length = 1; length <= sequence.size()/2); ++length) {
int freq = 1;
while ((freq + 1) * length <= sequence.size() and std::equal(sequence.end() - (freq + 1) * length, sequence.end() - freq * length, sequence.end() - length)) {
++freq;
if (freq > curl) {
curl = freq;
}
}
}
The while-loop does look quite horrendous. Basically, it tries to find matching periods in the end of the vector sequence, and if it finds a repeated period, it checks for how long it is extended. Any suggestions on better implementation or other, faster ways of writing this are really welcome!!
As requested some examples:
Say the vector sequence is { 1, 1, 2, 1, 1, 2 } it starts checking how many 2s are at the end of the vector, which is 1. Next, it checks how many 1, 2s are at the end, which is 1. Next, it checks 1, 1, 2 and finds that this is repeated 2 times. Thus, the curl is 2.
Say the vector sequence is { 2, 2, 2, 2 } it starts with 2 and finds 4 of these. Next, it checks 2, 2 and finds 2 of these. Thus, the curl is 4.
Since I have to find these curls for sequences up to about a length of 100 million, I really want to squeeze the most out of it. (I do use some mathematical approximation, but this part of the program still takes up about most of the time so I skipped that part).