Guest User

Untitled

a guest
Jun 20th, 2018
97
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 1.30 KB | None | 0 0
  1. #include <iostream>
  2. #include <sstream>
  3.  
  4. void rotate(int *arr, int count, int rotations) {
  5.     int *temp = new int[count];
  6.  
  7.     // copy overflowed elements to front
  8.     int *p1 = temp;
  9.     int *p2 = arr + (count - rotations);
  10.     while (p2 < (arr + count)) {
  11.         *p1++ = *p2++;
  12.     }
  13.  
  14.     // append remaining elements
  15.     p2 = arr;
  16.     while (p2 < (arr + (count - rotations))) {
  17.         *p1++ = *p2++;
  18.     }
  19.  
  20.     // replace original array with temp values
  21.     p1 = temp;
  22.     p2 = arr;
  23.     while (p1 < (temp + count)) {
  24.         *p2++ = *p1++;
  25.     }
  26.  
  27.     delete[] temp;
  28. }
  29.  
  30. int main() {
  31.     std::cout << "How many integers will you give me: ";
  32.     int count = 0;
  33.     std::cin >> count;
  34.     std::cin.ignore();
  35.  
  36.     std::cout << "Enter the sequence of " << count << " integers:" << std::endl;
  37.     std::string integers;
  38.     getline(std::cin, integers);
  39.     int *arr = new int[count];
  40.     std::istringstream stream(integers);
  41.     for (int i = 0; stream.good(); i++) {
  42.         stream >> arr[i];
  43.     }
  44.  
  45.     int rotations = 0;
  46.     std::cout << "How many positions to the right should it be shifted? ";
  47.     std::cin >> rotations;
  48.     rotations %= count;  // ensure rotations remain within count
  49.  
  50.     rotate(arr, count, rotations);
  51.  
  52.     for (int i = 0; i < count; i++) {
  53.         std::cout << arr[i];
  54.         if (i < (count - 1)) {
  55.             std::cout << " ";
  56.         }
  57.     }
  58.     std::cout << std::endl;
  59.  
  60.     delete[] arr;
  61.     return 0;
  62. }
Add Comment
Please, Sign In to add comment