fork download
  1. #include <iostream>
  2.  
  3. const unsigned dim = 3;
  4. typedef int array_type [dim][dim];
  5.  
  6. void average(array_type& dest, const array_type& src)
  7. {
  8. // corners:
  9. dest[ 0 ][ 0 ] =
  10. (src[ 0 ][ 0 ] + src[ 0 ][ 1 ] + src[ 1 ][ 0 ] + src[ 1 ][ 1 ])/4;
  11. dest[dim-1][ 0 ] =
  12. (src[dim-1][ 0 ] + src[dim-2][ 0 ] + src[dim-1][ 1 ] + src[dim-2][ 1 ])/4;
  13. dest[ 0 ][dim-1] =
  14. (src[ 0 ][dim-1] + src[ 1 ][dim-1] + src[ 0 ][dim-2] + src[ 1 ][dim-2])/4;
  15. dest[dim-1][dim-1] =
  16. (src[dim-1][dim-1] + src[dim-2][dim-1] + src[dim-1][dim-2] + src[dim-2][dim-2])/4;
  17.  
  18. // top, bottom, and sides:
  19. for (unsigned i = 1; i < dim - 1; ++i)
  20. {
  21. const unsigned j = dim - 1;
  22.  
  23. dest[0][i] =
  24. (src[0][i-1] + src[0][i] + src[0][i+1] + src[ 1 ][i-1] + src[ 1 ][i] + src[ 1 ][i+1])/6;
  25. dest[j][i] =
  26. (src[j][i-1] + src[j][i] + src[j][i+1] + src[j-1][i-1] + src[j-1][i] + src[j-1][i+1])/6;
  27.  
  28. dest[i][0] =
  29. (src[i-1][0] + src[i][0] + src[i+1][0] + src[i-1][ 1 ] + src[i][ 1 ] + src[i+1][ 1 ])/6;
  30. dest[i][j] =
  31. (src[i-1][j] + src[i][j] + src[i+1][j] + src[i-1][j-1] + src[i][j-1] + src[i+1][j-1])/6;
  32. }
  33.  
  34. // middle:
  35. for (unsigned i = 1; i < dim - 1; ++i)
  36. {
  37. for (unsigned j = 1; j < dim - 1; ++j)
  38. {
  39. dest[i][j] = (src[i-1][j-1] + src[i-1][j] + src[i-1][j+1] +
  40. src[ i ][j-1] + src[ i ][j] + src[ i ][j+1] +
  41. src[i+1][j-1] + src[i+1][j] + src[i+1][j+1]) / 9 ;
  42. }
  43. }
  44. }
  45.  
  46. void print(const array_type& array)
  47. {
  48. for (unsigned i = 0; i < dim; ++i)
  49. {
  50. for (unsigned j = 0; j < dim; ++j)
  51. std::cout << array[i][j];
  52. std::cout << '\n';
  53. }
  54. std::cout << '\n';
  55. }
  56.  
  57. int main()
  58. {
  59. array_type a =
  60. {
  61. 1, 2, 3,
  62. 4, 5, 6,
  63. 7, 8, 9
  64. };
  65.  
  66. array_type b = {};
  67.  
  68. print(a);
  69. print(b);
  70.  
  71. average(b, a);
  72. print(b);
  73. }
Success #stdin #stdout 0s 3340KB
stdin
Standard input is empty
stdout
123
456
789

000
000
000

334
455
667