Guest User

Untitled

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