Untitled

 avatar
unknown
plain_text
9 days ago
767 B
18
Indexable
std::vector<int> RotateRight(const std::vector<int>& vect,
                             unsigned int no_rotations) {
  unsigned int size = vect.size();
  std::vector<int> rot_vect(size);
  no_rotations = no_rotations % size;

  // Save elements that would be wrapped around
  std::vector<int> save(no_rotations);
  for (int save_index = no_rotations - 1, vect_index = size - 1;
       save_index >= 0;
       save_index--, vect_index--)
    save[save_index] = vect[vect_index];

  // Shift elements of vect in-place
  unsigned int rem = size - no_rotations;
  for (unsigned int i = 0; i < rem; i++)
    rot_vect[size - 1 - i] = vect[rem - 1 - i];

  // Copy saved elements
  for (unsigned int i = 0; i < no_rotations; i++) rot_vect[i] = save[i];

  return rot_vect;
}
Leave a Comment