Try using a boolean array to indicate whether a value exists or not. Use true to indicate that a number exists.
int main(void) { const unsigned int array_values[10] = {1, 2, 3, 3, 4, 5, 6, 7, 8, 9}; bool is_resident[10] = {false}; bool duplicate = false; unsigned int index = 0; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; duplicate = duplicate || is_resident[array[index]]; is_resident[array[index++]] = true; std::cout << "Duplicate found: " << (char *)(duplicate ? "true" : "false") << std::endl; return 0; }
The above code is not tested and does not specialize in this issue. This code has no other purpose in life, is not generalized.
Note. In this example, the cycles were not used or were not affected.
"There is always a third alternative." - Thomas Matthews
source share