fork download
  1. #include <iostream>
  2. #include <vector>
  3. #include <numeric>
  4. using namespace std;
  5.  
  6. void inputRoutine( vector<int> &a )
  7. {
  8. const int MAXNUM = 17;
  9. for ( int i = 1; i <= MAXNUM; i++ ) a.push_back( i );
  10. }
  11.  
  12.  
  13. void printRoutine(int COLS, vector<int> a, vector<int>& row_sum)
  14. {
  15. int size = a.size();
  16. int fullrows = size / COLS;
  17. int leftover = size % COLS;
  18. int rows = fullrows + ( leftover != 0 );
  19.  
  20. row_sum.resize(rows);
  21.  
  22. cout << "TABLE:\n";
  23. for ( int i = 0; i < rows; i++ )
  24. {
  25. int indexTop = 0;
  26. for ( int j = 0; j < COLS; j++ )
  27. {
  28. int index = indexTop + i;
  29. if ( i < fullrows || j < leftover )
  30. {
  31. cout << a[index];
  32. row_sum[i] += a[index];
  33. }
  34. cout << '\t';
  35. if ( j < leftover ) indexTop += rows; // top-of-column 1-d index for the number in this column
  36. else indexTop += fullrows;
  37. }
  38. cout << '\n';
  39. }
  40.  
  41. if (COLS == 1)
  42. {
  43. row_sum[0] = std::accumulate(std::begin(row_sum), std::end(row_sum), 0);
  44. row_sum.resize(1);
  45. }
  46. }
  47.  
  48.  
  49. int main()
  50. {
  51. vector<int> a;
  52. inputRoutine( a );
  53.  
  54. for (int COLS = 1; COLS < 6; ++COLS)
  55. {
  56. vector<int> row_sum;
  57. printRoutine( COLS, a, row_sum );
  58.  
  59. std::cout << '\n' << COLS << '\t';
  60. for (int i : row_sum)
  61. std::cout << i << ' ';
  62. std::cout << std::endl;
  63. std::cout << std::endl;
  64. }
  65. }
Success #stdin #stdout 0s 15240KB
stdin
Standard input is empty
stdout
TABLE:
1	
2	
3	
4	
5	
6	
7	
8	
9	
10	
11	
12	
13	
14	
15	
16	
17	

1	153 

TABLE:
1	10	
2	11	
3	12	
4	13	
5	14	
6	15	
7	16	
8	17	
9		

2	11 13 15 17 19 21 23 25 9 

TABLE:
1	7	13	
2	8	14	
3	9	15	
4	10	16	
5	11	17	
6	12		

3	21 24 27 30 33 18 

TABLE:
1	6	10	14	
2	7	11	15	
3	8	12	16	
4	9	13	17	
5				

4	31 35 39 43 5 

TABLE:
1	5	9	12	15	
2	6	10	13	16	
3	7	11	14	17	
4	8				

5	42 47 52 12