fork(1) download
  1. #include <algorithm>
  2. #include <iostream>
  3. #include <vector>
  4. using namespace std;
  5.  
  6. bool hasSingleCycle(vector<int> array) {
  7.  
  8. //doesn't matter where you start in the cycle
  9. //if there is a cycle, all elements will be in the valid cycle
  10. vector<int> visitedIndex;
  11. int currIndex = 0;
  12. int indexVal = array.at(0);
  13. visitedIndex.push_back(0);
  14.  
  15. while (visitedIndex.size() != array.size() + 1) {
  16. currIndex = currIndex + indexVal;
  17. if (currIndex < 0) {
  18. cout << currIndex << " % " << array.size() << endl;
  19. currIndex = currIndex % array.size();
  20. cout << currIndex << endl;
  21. currIndex = array.size() + currIndex;
  22. cout << currIndex << endl;
  23. }
  24. else if (currIndex >= array.size()) {
  25. currIndex = currIndex % array.size();
  26. }
  27. visitedIndex.push_back(currIndex);
  28. indexVal = array.at(currIndex);
  29. }
  30.  
  31. for (int i = 0; i < array.size(); i++) {
  32. if (find(visitedIndex.begin(), visitedIndex.end(), i) == visitedIndex.end()) {
  33. return false;
  34. }
  35. }
  36.  
  37. if (visitedIndex.at(array.size()) != 0) {
  38. return false;
  39. }
  40. return true;
  41. }
  42.  
  43. int main() {
  44. // int z = -1%3;
  45. // cout << z << endl;
  46. vector<int> x = {-1, 2, 2};
  47. bool y = hasSingleCycle(x);
  48. return 0;
  49. }
  50.  
Runtime error #stdin #stdout #stderr 0s 4176KB
stdin
Standard input is empty
stdout
-1 % 3
0
3
stderr
terminate called after throwing an instance of 'std::out_of_range'
  what():  vector::_M_range_check: __n (which is 3) >= this->size() (which is 3)