The problem:
Treat an array as if it is circular; out-of-bounds indices "wrap around" the array to become in-bounds.
Current solution:
// roudedArray.cpp
#include <iostream>
template <typename T, int N>
int wrapAroundArray(int i, T(&ThisArray)[N])
{
// "wrap" i around ThisArray, landing on a valid index
while (i < 0) { i += N; }
while (i >= N) { i -= N; }
return i;
}
std::string words[] = { "this", "and", "that" };
int main()
{
for (int i = -9; i < 10; i++)
{
int adj = wrapAroundArray(i, words);
std::cout << "i: " << i;
std::cout << ", adjusted index: " << adj;
std::cout << ", word: " << words[adj] << std::endl;
}
}
Output (compile with g++ roundedArray.cpp
):
i: -9, adjusted index: 0, word: this i: -8, adjusted index: 1, word: and i: -7, adjusted index: 2, word: that i: -6, adjusted index: 0, word: this i: -5, adjusted index: 1, word: and i: -4, adjusted index: 2, word: that i: -3, adjusted index: 0, word: this i: -2, adjusted index: 1, word: and i: -1, adjusted index: 2, word: that i: 0, adjusted index: 0, word: this i: 1, adjusted index: 1, word: and i: 2, adjusted index: 2, word: that i: 3, adjusted index: 0, word: this i: 4, adjusted index: 1, word: and i: 5, adjusted index: 2, word: that i: 6, adjusted index: 0, word: this i: 7, adjusted index: 1, word: and i: 8, adjusted index: 2, word: that i: 9, adjusted index: 0, word: this
I'd prefer an arithmetic (constant-time) solution that produces the same results. Any suggestions?