[ create a new paste ] login | about

Link: http://codepad.org/GrN7XEvS    [ raw code | output | fork ]

C++, pasted on Apr 11:
#include <iostream>
#include <iomanip>
#include <algorithm>
#include <numeric>
#include <cstdlib>
#include <ctime>

class RandomNumber {
    int bottom;
    int top;
public:
    RandomNumber(const int _bottom, const int _top) : bottom(_bottom), top(_top) {}
    int operator () () const { return rand() % ( top - bottom + 1 ) + bottom; }
};

void dump_row(const int * row, size_t size, const size_t width) {
    while ( size-- )
        std::cout << std::setw(width) << *row++;
    std::cout << std::endl;
}

void dump_matrix(const int ** matrix, size_t rows, size_t columns, const size_t width) {
    while ( rows-- )
        dump_row(*matrix++, columns, width);
}

int main() {
    const size_t WIDTH(4);
    const int BOTTOM(0);
    const int TOP(99);
    size_t rows, columns;
    int ** matrix;

    /*
    std::cout << "Rows: ";
    std::cin >> rows;
    std::cout << "Columns: ";
    std::cin >> columns;
    */
    rows = 5;
    columns = 10;

    srand(time(0));

    matrix = new int * [ rows ];
    for ( size_t i = 0; i < rows; ++i ){
        matrix[i] = new int [ columns ];
        std::generate_n(matrix[i], columns, RandomNumber(BOTTOM, TOP));
    }

    std::cout << "Before:" << std::endl;
    dump_matrix((const int**)matrix, rows, columns, WIDTH);

    for ( size_t i = 0; i < rows; ++i ) {
        int * pMax = (int*) std::max_element(matrix[i], matrix[i] + columns);
        *pMax = std::accumulate(matrix[i], pMax, 0);
    }

    std::cout << "After:" << std::endl;
    dump_matrix((const int**)matrix, rows, columns, WIDTH);

    for ( size_t i = 0; i < rows; ++i )
        delete [] matrix[i];
    delete [] matrix;

    return 0;
}


Output:
1
2
3
4
5
6
7
8
9
10
11
12
Before:
   6   4  30  83  89  99  54  20  73  82
  95  52  37  50  50  41  73  22  71  31
  76  78   0  31  45   8  73  79  26  12
   9  32  68  39  67  57  91  73  30  64
  56  25  16  45  27  18  86   1  40  58
After:
   6   4  30  83  89 212  54  20  73  82
   0  52  37  50  50  41  73  22  71  31
  76  78   0  31  45   8  73 311  26  12
   9  32  68  39  67  57 272  73  30  64
  56  25  16  45  27  18 187   1  40  58


Create a new paste based on this one


Comments: