Yeah, the v[i-1] - v[i-2] > 1 part is meant to complete the same check.
Also, sorry! One part of my program is actually incorrect (I’ll get to that in a minute).
Here is how it works:
In order for the array to be a valid rainbow, we know it has to go from 1 to 2 to 3, etc.
We also know that there can be any number of 1’s, 2’s, etc. So there are two valid transitions between array elements:
- where v[i] = v[i+1], e.g. 3 → 3
- where v[i] + 1 = v[i+1], e.g. 2 → 3
From the initial check before the final loop (v == 1), we can confirm that the starting value is 1.
At the final check, we also know that the middle element is 7 (v[l/2] == 7).
If either of them is false, then we can already say “no” is our answer, otherwise this check will work:
Knowing that our starting value is 1 and our mid value is 7, all we need to make sure, is that between each element, the value is either staying the same, or increasing by one.
If it does that, and starts at 1 and ends at 7 at the middle, then we know it made a valid half of the rainbow, because it would have had to pass through all valid numbers in an increasing way to reach 7 from 1.
That is what the if statement is looking for, it checks if that difference isn’t 0 or 1, in which case an invalid transition is made and the result will be “no”.
Since we are also making sure the value on the first half is the same as on the second half, this means we have a valid complete rainbow as well.
I need to add though, that the if statement I used actually isn’t correct, I forgot to add a check for a negative transition, because obviously we don’t want it going from a larger value back down to a smaller one, e.g. 1->2->1->2 looks correct to the current if statement even though it isn’t.
You will want to change the if to:
(i > 1 && (v[i-1] - v[i-2] > 1 || v[i-1] - v[i-2] < 0)
,to account for the negative transition as well.