task3.cpp 2.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. #include <iostream>
  2. void cyclic_shift(int**& matrix, int rows, int cols, const std::string& direction, int shift_count, bool rows_shift, bool cols_shift) {
  3. if (rows_shift) {
  4. shift_count %= rows;
  5. int** temp = new int*[rows];
  6. for (int i = 0; i < rows; ++i) {
  7. temp[i] = new int[cols];
  8. }
  9. if (direction == "up") {
  10. for (int i = 0; i < rows; ++i) {
  11. std::copy(matrix[(i + shift_count) % rows], matrix[(i + shift_count) % rows] + cols, temp[i]);
  12. }
  13. } else if (direction == "down") {
  14. for (int i = 0; i < rows; ++i) {
  15. std::copy(matrix[(i - shift_count + rows) % rows], matrix[(i - shift_count + rows) % rows] + cols, temp[i]);
  16. }
  17. }
  18. for (int i = 0; i < rows; ++i) {
  19. delete[] matrix[i];
  20. }
  21. delete[] matrix;
  22. matrix = temp;
  23. }
  24. if (cols_shift) {
  25. shift_count %= cols;
  26. for (int i = 0; i < rows; ++i) {
  27. if (direction == "right") {
  28. int* temp = new int[cols];
  29. for (int j = 0; j < cols; ++j) {
  30. temp[j] = matrix[i][(j - shift_count + cols) % cols];
  31. }
  32. std::copy(temp, temp + cols, matrix[i]);
  33. delete[] temp;
  34. } else if (direction == "left") {
  35. int* temp = new int[cols];
  36. for (int j = 0; j < cols; ++j) {
  37. temp[j] = matrix[i][(j + shift_count) % cols];
  38. }
  39. std::copy(temp, temp + cols, matrix[i]);
  40. delete[] temp;
  41. }
  42. }
  43. }
  44. }
  45. int main() {
  46. int rows = 3, cols = 3;
  47. int** matrix = new int*[rows];
  48. for (int i = 0; i < rows; ++i) {
  49. matrix[i] = new int[cols];
  50. }
  51. matrix[0][0] = 1; matrix[0][1] = 2; matrix[0][2] = 3;
  52. matrix[1][0] = 4; matrix[1][1] = 5; matrix[1][2] = 6;
  53. matrix[2][0] = 7; matrix[2][1] = 8; matrix[2][2] = 9;
  54. std::string direction = "right";
  55. int shift_count = 1;
  56. cyclic_shift(matrix, rows, cols, direction, shift_count, false, true);
  57. for (int i = 0; i < rows; ++i) {
  58. for (int j = 0; j < cols; ++j) {
  59. std::cout << matrix[i][j] << " ";
  60. }
  61. std::cout << std::endl;
  62. }
  63. for (int i = 0; i < rows; ++i) {
  64. delete[] matrix[i];
  65. }
  66. delete[] matrix;
  67. return 0;
  68. }