Advertisement
Guest User

Untitled

a guest
Jan 19th, 2020
70
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C++ 2.16 KB | None | 0 0
  1. #include <cstddef>
  2. #include <iostream>
  3. #include <cmath> // fabs
  4. using namespace std;
  5.  
  6. // Вариант 1. Массив указателей на строки.
  7. bool is_digmatrix(double const* const* matrix, size_t rows, size_t cols)
  8. {
  9.  
  10. for (size_t i = 0; i < rows; ++i)
  11. {
  12.     int k=i,j=0;
  13.     while(k<rows && j<cols){
  14.         if(matrix[i][0]!=matrix[k][j])return false;
  15.         k++;
  16.         j++;
  17.     }
  18. }
  19.  
  20. for (size_t i = 0; i < cols; ++i)
  21. {
  22.     int k=i,j=0;
  23.     while(k<cols && j<rows){
  24.         if(matrix[0][i]!=matrix[j][k])return false;
  25.         k++;
  26.         j++;
  27.     }
  28. }
  29.  
  30.  
  31. // Все элементы "хорошие".
  32. return true;
  33. }
  34.  
  35. // Вариант 2. Упакованный массив.
  36. bool is_digmatrix(double const matrix[], size_t rows, size_t cols)
  37. {
  38. for (size_t i = 0; i < cols*rows; i+=rows)
  39. {
  40.     for (size_t j = i; j < cols*rows; j+=rows+1)
  41.     {
  42.     if(matrix[i]!=matrix[j]){return false;}
  43.     }
  44. }
  45. for (size_t i = 0; i < cols; ++i)
  46. {
  47.     for (size_t j = i; j < cols*rows; j+=rows+1)
  48.     {
  49.     if(matrix[i]!=matrix[j]){return false;}
  50.     }
  51. }
  52.  
  53. // Все элементы "хорошие".
  54. return true;
  55. }
  56.  
  57. // Обёртка для теста упакованного массива как массива указателей.
  58. bool is_digmatrix_packed_adapter
  59. (double const matrix[], size_t rows, size_t cols)
  60. {
  61. // Создадим временный массив для хранения указателей на строки.
  62. auto r = new double const*[rows];
  63. for (size_t i = 0; i < rows; ++i, matrix += cols)
  64. r[i] = matrix;
  65. // Вызовем функцию is_01matrix.
  66. bool result = is_01matrix(r, rows, cols);
  67. // Удалим массив.
  68. delete[] r;
  69. // Вернём полученный результат.
  70. return result;
  71. }
  72.  
  73. // Тест.
  74. int test_is_digmatrix
  75. (bool (&isdig)(double const matrix[], size_t rows, size_t cols))
  76. {
  77. double m[]
  78. {
  79. 1 2 3 4
  80. 2 1 2 3
  81. 3 2 1 2
  82. };
  83.  
  84. if (!isdig(m, 3, 4))
  85. return 1;
  86.  
  87.  
  88. return 0;
  89. }
  90.  
  91. int main()
  92. {
  93. cout << "is_digmatrix tests (should write 0 0): ";
  94. cout << test_is_digmatrix(is_digmatrix) << ' ';
  95. cout << test_is_digmatrix(is_digmatrix_packed_adapter);
  96. return 0;
  97. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement