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) {
- int *temp = new int[count];
- // copy overflowed elements to front
- 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();
- 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);
- for (int i = 0; stream.good(); i++) {
- stream >> arr[i];
- }
- int rotations = 0;
- std::cout << "How many positions to the right should it be shifted? ";
- std::cin >> rotations;
- rotations %= count; // ensure rotations remain within count
- 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