1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129
|
/*
Create a program that, given a matrix, sums the number in lines and then order them in increasing order.
*/
#include <iostream>
#include <fstream>
#include <cstdlib>
using namespace std;
struct position{
int summation;
int pos;
};
//Prototypes Functions
void LoadMatrix(int ncol, int nrow, int** mat);
void RowSum(int nrow, int ncol, position* sum, int** mat);
void RowsOrder(int nrow, int ncol, position* sum);
void PrintMatrix(int nrow, int ncol, position* sum, int** mat);
fstream file;
const int N=100;
int main(int argc, char** argv) {
int** mat;
int ncol=0, nrow=0;
char* row=new char [N];
int numbmat=0;
int vect[N];
file.open("Matrix.txt", ios::in);
if(!file) {
cout<<"File not found!\n";
exit(1);
}
int i=0;
//Calculating number of lines.
while(!file.eof()) {
file.getline(row, 100);
i++;
}
nrow=i;
i=0;
file.seekg(0);
//Calculating all the number of the matrix.
while(!file.eof()) {
file>>numbmat;
i++;
}
//Calculating number of columns.
ncol=i/nrow;
//Allocating matrix.
mat=new int* [nrow];
for(int j=0; j<nrow; j++) {
mat[j]=new int [ncol];
}
//Allocating array of struct.
position* sum= new position [nrow];
LoadMatrix(ncol, nrow, mat);
RowSum(nrow, ncol, sum, mat);
RowsOrder(nrow, ncol, sum);
PrintMatrix(nrow, ncol, sum, mat);
system("pause");
return 0;
}
/*
Function that load the matrix from the file.
*/
void LoadMatrix(int ncol, int nrow, int** mat) {
file.seekg(0);
for(int r=0; r<nrow; r++) {
for(int c=0; c<ncol; c++) {
file>>mat[r][c];
}
}
}
/*
Function that sums the number in each row.
*/
void RowSum(int nrow, int ncol, position* sum, int** mat) {
for(int r=0; r<nrow; r++) {
int a=0;
for(int c=0; c<ncol; c++) {
a=a+mat[r][c];
}
sum[r].summation=a;
sum[r].pos=r;
}
}
/*
Function that sort the rows.
*/
void RowsOrder(int nrow, int ncol, position* sum) {
int temp1=0, temp2=0;
int i=0;
do{
for(int j=0; j<nrow-1; j++) {
if(sum[j].summation>sum[j+1].summation) {
temp1=sum[j].summation;
sum[j].summation=sum[j+1].summation;
sum[j+1].summation=temp1;
temp2=sum[j].pos;
sum[j].pos=sum[j+1].pos;
sum[j+1].pos=temp2;
}
}
i++;
}while(i<ncol);
}
/*
Function that print the matrix.
*/
void PrintMatrix(int nrow, int ncol, position* sum, int** mat) {
for(int r=0; r<nrow; r++) {
for(int c=0; c<ncol; c++) {
cout<<mat[sum[r].pos][c]<<" ";
}
cout<<endl;
}
}
|