C/C++

Двумерный массив и строки

Поменять столбцы, содержащие больше всего четных и больше всего нечетных элементов.
например массив 3 на 3
Oguz M
Oguz M
201
#include <algorithm>
#include <iostream>
#include <iomanip>
#include <ctime>
#include <utility>
using namespace std;

int main() {
int matrix[50][50];
cout << "Enter a number of rows (no more than 50): ";
int row;
cin >> row;
cout << "Enter a number of columns (no more than 50): ";
int column;
cin >> column;

srand(time(0));
for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j)
cout << setw(5) << (matrix[i][j] = rand() % 41 - 20);
cout << "\n";
}
cout << "\n";

int indj1 = 0, indj2 = 0, cnt1 = 0, cnt2 = 0;
for (int j = 0; j < column; ++j) {
int c1 = 0, c2 = 0;
for (int i = 0; i < row; ++i) (matrix[i][j] & 1 ? ++c1 : ++c2);
if (c1 > cnt1) cnt1 = c1, indj1 = j;
if (c2 > cnt2) cnt2 = c2, indj2 = j;
}

if (indj1 != indj2) {
for (int i = 0; i < row; ++i) swap(matrix[i][indj1], matrix[i][indj2]);
}

for (int i = 0; i < row; ++i) {
for (int j = 0; j < column; ++j)
cout << setw(5) << matrix[i][j];
cout << "\n";
}
cout << "\n";

return 0;
}
Михаил Бойко
Михаил Бойко
6 243
Лучший ответ
#include <iostream>
#include <iomanip>
#include <cstdlib>
#include <ctime>
using namespace std;
int main() {
size_t n, m;
cout << "Rows: ";
cin >> n;
cout << "Columns: ";
cin >> m;
puts("");
auto matrix = new int* [n];
for (auto i = 0U; i < n; ++i) {
matrix[i] = new int[m];
}
srand(unsigned(time(nullptr)));
for (auto i = 0U; i < n; ++i) {
for (auto j = 0U; j < m; ++j) {
matrix[i][j] = 1 + rand() % 99;
}
}
for (auto i = 0U; i < n; ++i) {
for (auto j = 0U; j < m; ++j) {
cout << setw(4) << matrix[i][j];
}
puts("");
}
puts("");
int max_count_odd = 0;
int max_count_even = 0;
int pos_odd = -1;
int pos_even = -1;
for (auto j = 0U; j < m; ++j) {
int odd = 0;
int even = 0;
for (auto i = 0U; i < n; ++i) {
matrix[i][j] & 1 ? ++odd : ++even;
}
if (max_count_odd < odd) {
max_count_odd = odd;
pos_odd = j;
}
if (max_count_even < even) {
max_count_even = even;
pos_even = j;
}
}
if (pos_odd == -1) {
puts("No odd found!");
} else if (pos_even == -1) {
puts("No even found!");
} else if (pos_odd == pos_even) {
puts("Columns match!");
} else {
cout << "Swap columns " << pos_odd << " and " << pos_even << ":\n\n";
for (auto i = 0U; i < n; ++i) {
swap(matrix[i][pos_odd], matrix[i][pos_even]);
}
for (auto i = 0U; i < n; ++i) {
for (auto j = 0U; j < m; ++j) {
cout << setw(4) << matrix[i][j];
}
puts("");
}
}
for (auto i = 0U; i < n; ++i) {
delete[] matrix[i];
}
delete[] matrix;
system("pause > nul");
}
Леонид Киселев
Леонид Киселев
58 610