Skip to the content of the web site.

Project W.2: Shift and circular shift

Problem

Given an array, it may be desirable to shift or rotate the

Implement the following four functions that perform the equivalent of the left- and right-bit-shifting operators, but on the entries of an array. For the shift functions, a shift of order $n$ should introduce $n$ new zero entries at the appropriate location. For the circular shift functions, the entries that fall off are moved to the back of the array.

All of these functions operate in-place, meaning that they modify the matrix that is passed.

For example, the following code would modify the array as described:

    int array[7]{12, 13, 14, 15, 16, 17, 18};
     left_shift( array, 7, 1 );  // Array becomes {13, 14, 15, 16, 17, 18,  0}
    right_shift( array, 7, 2 );  // Array becomes { 0,  0, 13, 14, 15, 16, 17}
     left_circular_shift( array, 7, 3 );
                                 // Array becomes {14, 15, 16, 17,  0,  0, 13}
    right_circular_shift( array, 7, 4 );
                                 // Array becomes {17,  0,  0, 13, 14, 15, 16}

2. Integer implementation

Implement the above functions for an array of type int.

2.1 Required background

  • modulus operator
  • loops
  • arrays

2.2 Function prototypes

void  left_shift( int array[], std::size_t capacity, std::size_t n );
void right_shift( int array[], std::size_t capacity, std::size_t n );
void  left_circular_shift( int array[], std::size_t capacity, std::size_t n );
void right_circular_shift( int array[], std::size_t capacity, std::size_t n );

Templated implementation

For templated implementations, you could use 0, but it is better to use the default value of the templated type: T{}.

template <typename T>
void  left_shift( T array[], std::size_t capacity, std::size_t n );

template <typename T>
void right_shift( T array[], std::size_t capacity, std::size_t n );

template <typename T>
void  left_circular_shift( T array[], std::size_t capacity, std::size_t n );

template <typename T>
void right_circular_shift( T array[], std::size_t capacity, std::size_t n );