Disclaimer, I'm new to OOP, but have experience in haskell and javascript.
Essentially, the challenge was to create a program which would shift an array a given amount of times to the left and then print the result.
I've tried to make this more extendable by allowing the option to shift to the right.
My code is
#include <iostream>
#include <vector>
using namespace std;
vector<int> rotate(vector<int> myVector, int direction, int count);
vector<int> rotate(vector<int> myVector, int direction);
void print(vector<int> rotatedVector);
void print(vector<int> rotatedVector){
for(int i = 0; i < rotatedVector.size(); i++){
cout << rotatedVector[i] << endl;
}
}
vector<int> rotate(vector<int> myVector, int direction, int count){
while(count > 0){
myVector = rotate( myVector, direction); // should I create a new variable, or just overwrite myVector each time?
--count;
}
return myVector;
}
vector<int> rotate(vector<int> myVector, int direction){
const int length = myVector.size();
vector<int> rotatedVector(length);
for(int i = 0; i < myVector.size(); i++){
rotatedVector.at(i) = myVector.at((length+i-direction)%length);
}
return rotatedVector;
}
int main(){
// Array to rotate
int arr[5] = {1,2,3,4,5};
// Times to rotate
const int count = 2;
// Creating a vector object out of array
// Should I have worked with the array given?
int n = sizeof(arr) / sizeof(arr[0]);
vector<int> myVector(arr, arr + n);
enum direction {left = -1, right = 1}; // should this be global?
myVector = rotate(myVector, left, count);
print(myVector);
// Could potentially turn vector back into array?
return 0 ;
}
My design questions are...
Is this extendable enough, how could it be made more so?
Should the enums be made global?
Should I have used multiple functions instead of using enums to make the rotation functions generic? (e.g a right rotation function, and a left one)
Should I have kept with the array, instead of creating a vector from it?
- Was overloading the function necessary?
The most important thing I would like to clarify from this review, is the concept of "state" in these types of programming puzzles (done in C++/OOP)
The line which overwrites the vector is...
myVector = rotate( myVector, direction);
Is it better form to perhaps implement something like...
myVector.rotate(direction);
and thus action on the same object each time? (and if so why)
When would I use one over the other?
In my head, I feel as though it would be best to make the vector immutable and keep creating a new one each time, but am unsure and slightly confused about which one to use.