Created
March 29, 2018 12:48
-
-
Save alepez/406a8ba9a51c569f946225e4306a55ea to your computer and use it in GitHub Desktop.
Fix a sequence in a modular range, keeping direction
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
template <typename T> | |
T fix_modular_sequence(T&& seq, const typename T::value_type modulus) { | |
const auto threshold = modulus / 2.0; | |
auto it = seq.begin(); | |
auto prev = *it; | |
while (it != seq.end()) { | |
++it; | |
auto& curr = *it; | |
auto diff = curr - prev; | |
if (std::abs(diff) > threshold) curr -= (diff < 0 ? -1 : 1) * modulus; | |
prev = curr; | |
} | |
return std::move(seq); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
[1,2,3,4,5,6,7,8,9, 0, 1, 2, 3, 4, 5, 4, 3, 2, 1, 0,9,7,4,2, 9, 7, 6]
Becomes:
[1,2,3,4,5,6,7,8,9,10,11,12,13,14,15,14,13,12,11,10,9,7,4,2,-1,-3,-4]