Skip to content

Instantly share code, notes, and snippets.

@itayB
Created September 15, 2016 15:36
Show Gist options
  • Select an option

  • Save itayB/bfa8129ec248f9611da2eb40c31dd773 to your computer and use it in GitHub Desktop.

Select an option

Save itayB/bfa8129ec248f9611da2eb40c31dd773 to your computer and use it in GitHub Desktop.
#include <iostream>
#include <stdexcept>
using namespace std;
template <class T> class CircularArray {
private:
int size;
int head;
T* arr;
int convert(int i) {
return (head + i) % size;
}
public:
/* Constructor */
CircularArray(int size) {
if (size <= 0)
throw std::invalid_argument( "illegal value" );
arr = new T[size];
head = 0;
this->size = size;
}
/* Destructor */
virtual ~CircularArray() {
delete arr;
}
void shift(int shiftRight) {
// TODO: neg input
head = (head + shiftRight) % size;
}
T get(int i) {
if (i < 0 || i >= size)
throw std::invalid_argument( "illegal value" );
return arr[convert(i)];
}
void set(int i, T t) {
if (i < 0 || i >= size)
throw std::invalid_argument( "illegal value" );
arr[convert(i)] = t;
}
void print() {
cout << "[";
for (int i=0 ; i < size ; i++) {
if (i)
cout << ", ";
cout << this->get(i);
}
cout << "]" << endl;
}
};
int main() {
int n = 10;
CircularArray<int> cArr(n);
// fill array
for (int i=0 ; i < n ; i++) {
cArr.set(i,i+1);
}
cArr.print();
cArr.shift(3);
cArr.print();
cArr.shift(2);
cArr.print();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment