Created
May 29, 2018 19:49
-
-
Save mexus/91e2b314375e9a827b8f3f69ee82a6e6 to your computer and use it in GitHub Desktop.
Some stuff with a matrix
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#include <algorithm> | |
#include <array> | |
#include <iostream> | |
template <class T, size_t Columns, size_t Rows> | |
using Matrix = std::array<std::array<T, Columns>, Rows>; | |
template <class T, size_t Columns, size_t Rows> | |
static void print_matrix(const Matrix<T, Columns, Rows> &matrix) { | |
for (size_t i = 0; i != Rows; ++i) { | |
for (size_t j = 0; j != Columns; ++j) { | |
std::cout << matrix[i][j] << "\t"; | |
} | |
std::cout << "\n"; | |
} | |
} | |
template <class T, size_t Columns, size_t Rows> | |
static Matrix<T, Columns, Rows> generate_matrix() { | |
Matrix<T, Columns, Rows> matrix; | |
for (size_t i = 0; i != Rows; ++i) { | |
auto &row = matrix[i]; | |
// FIXME: use proper random functionality. | |
std::generate(row.begin(), row.end(), | |
[]() { return std::rand() % 50; }); | |
} | |
return matrix; | |
} | |
template <class Iterator> | |
static void process_row(Iterator begin, Iterator end) { | |
auto min_and_max = std::minmax_element(begin, end); | |
std::iter_swap(begin, min_and_max.second); | |
std::iter_swap(--end, min_and_max.first); | |
} | |
template <class T, size_t Columns, size_t Rows> | |
static void process_matrix(Matrix<T, Columns, Rows> &matrix) { | |
static_assert(Rows != 0, "Matrix should have at least one row"); | |
static_assert(Columns != 0, "Matrix should have at least one column"); | |
std::for_each(matrix.begin(), matrix.end(), | |
[](std::array<T, Columns> &row) { | |
process_row(row.begin(), row.end()); | |
}); | |
} | |
int main() { | |
constexpr const unsigned columns = 5; | |
constexpr const unsigned rows = 6; | |
// FIXME: use proper random functionality. | |
srand(static_cast<unsigned>(time(nullptr))); | |
auto matrix = generate_matrix<int, columns, rows>(); | |
std::cout << "Matrix before transformation:\n"; | |
print_matrix(matrix); | |
std::cout << "\n"; | |
process_matrix(matrix); | |
std::cout << "Matrix after transformation:\n"; | |
print_matrix(matrix); | |
std::cout << "\n"; | |
// system("pause"); | |
return 0; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment