1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86
|
template <typename T>
T** allocate_2d_matrix(int N1, int N2)
{
T** p = new T*[N1];
for (int i=0; i<N2; i++)
p[i] = new T[N2];
return (p);
}
template <typename T>
void destroy_matrix(T** p, int N1, int N2)
{
for (int i=0; i<N2; i++)
delete [] p[i];
delete [] p;
}
template <typename T>
void fill(T** p, int N1, int N2)
{
for (int i=0; i<N1; i++)
for (int j=0; j<N2; j++)
p[i][j] = rand();
}
template <typename T>
T sum_row(T** p, int N1, int N2, int row)
{
assert(row < N1);
return (std::accumulate(p[row], p[row] + N2, 0));
}
template <typename T>
T sum_col(T** p, int N1, int N2, int col)
{
assert(col < N2);
int sum = 0;
for (int i=0; i<N1; i++)
sum += p[i][col];
return (sum);
}
template <typename T>
bool is_magic(T** p, int N1, int N2)
{
int sum_base = sum_row(p, N1, N2, 0);
for (int i=1; i<N1; i++)
{
if (sum_base != sum_row(p, N1, N2, i))
return (false);
}
for (int i=1; i<N2; i++)
{
if (sum_base != sum_col(p, N1, N2, i))
return (false);
}
int sum_diag1 = 0;
int sum_diag2 = 0;
for (int i=0; i<N1; i++)
for (int j=0; j<N2; j++)
{
sum_diag1 += p[i][j];
sum_diag2 += p[i][N2-j-1];
}
return
(sum_base == sum_diag1) &&
(sum_base == sum_diag2);
}
void test_matrix()
{
const int N = 2;
int** p = allocate_2d_matrix<int>(N, N);
fill(p, N, N);
std::cout << is_magic(p, N, N) << std::endl;
destroy_matrix(p, N, N);
}
|