Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #include <iostream>
- #include <sstream>
- void rotate(int *arr, int count, int rotations) {
- rotations %= count; // ensure rotations remain within count
- // copy overflowed elements to front of temp array
- int *temp = new int[count];
- int *p1 = temp;
- int *p2 = arr + (count - rotations);
- while (p2 < (arr + count)) {
- *p1++ = *p2++;
- }
- // append remaining elements
- p2 = arr;
- while (p2 < (arr + (count - rotations))) {
- *p1++ = *p2++;
- }
- // replace original array with temp values
- p1 = temp;
- p2 = arr;
- while (p1 < (temp + count)) {
- *p2++ = *p1++;
- }
- delete[] temp;
- }
- int main() {
- std::cout << "How many integers will you give me: ";
- int count = 0;
- std::cin >> count;
- std::cin.ignore();
- if (count <= 0) {
- std::cerr << "You must enter a positive value." << std::endl;
- return 1;
- }
- std::cout << "Enter the sequence of " << count << " integers:" << std::endl;
- std::string integers;
- getline(std::cin, integers);
- int *arr = new int[count];
- std::istringstream stream(integers);
- int i = 0;
- while (stream.good()) {
- stream >> arr[i];
- i++;
- }
- if (i != count) {
- std::cerr << "You did not enter " << count << " integers." << std::endl;
- return 2;
- }
- int rotations = 0;
- std::cout << "How many positions to the right should it be shifted? ";
- std::cin >> rotations;
- if (rotations < 0) {
- std::cerr << "You must enter a positive number of rotations." << std::endl;
- return 3;
- }
- rotate(arr, count, rotations);
- for (int i = 0; i < count; i++) {
- std::cout << arr[i];
- if (i < (count - 1)) {
- std::cout << " ";
- }
- }
- std::cout << std::endl;
- delete[] arr;
- return 0;
- }
Add Comment
Please, Sign In to add comment