Skip to content

Instantly share code, notes, and snippets.

@alepez
Created March 29, 2018 12:48
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save alepez/406a8ba9a51c569f946225e4306a55ea to your computer and use it in GitHub Desktop.
Save alepez/406a8ba9a51c569f946225e4306a55ea to your computer and use it in GitHub Desktop.
Fix a sequence in a modular range, keeping direction
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);
}
@alepez
Copy link
Author

alepez commented Mar 29, 2018

[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]

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment