The goal of the program is to generate a multidimensional array, of variable size, the number of columns being the numbers of political parties, the number of rows being the "round" we're in, and the entries of the first row being the number of votes each political party got, then as you get into the second row, round 2, you divide all the values in the first row by 2, in round 3 you divide the values in the first row by 3, and the same thing goes for how many rows the thing has.
I got all that done, but after those operations are over, I want to be able to find the N largest elements, n being the number of rows, and place those elements in a vector, for some reason I can't seem to find, when I run it nothing is displayed on the console, when I get to the part where I want it to sort out the elements, it blacks out, and then crashes.
I've tried changing things around, I don't really think the problem is in the algorithm itself, as I've tried it with static arrays that I've filled randomly, and it sorted those out just fine. Like I said I don't really know where the problem is so I'll show a large part, I've cut out everything not pertinent.
double** ELEITORAL;
void bubble_sort(double** ELEITORAL)
{
int x, y;
double tItem;
int PassCount;
bool Mudou;
for (PassCount = 0; PassCount < (MAX_rows * MAX_columns); PassCount++)
{
//orders the rows
for (y = 0; y < MAX_columns; y++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (x = 1; x < MAX_rows; x++)
{
if (ELEITORAL[x - 1][y] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x - 1][y];
ELEITORAL[x - 1][y] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
}
}
}
}
//ORDERS THE COLUMNS
for (x = 0; x < MAX_rows; x++)
{
Mudou = true;
while (Mudou)
{
Mudou = false;
for (y = 1; y < MAX_columns; y++)
{
if (ELEITORAL[x][y - 1] > ELEITORAL[x][y])
{
Mudou = true;
tItem = ELEITORAL[x][y - 1];
ELEITORAL[x][y - 1] = ELEITORAL[x][y];
ELEITORAL[x][y] = tItem;
cout << "entrei";
system("pause");
}
}
}
}
}
}
void DisplayTheArray(double** ELEITORAL)
{
for (int y = 0; y < MAX_columns; y++)
{
for (int x = 0; x < MAX_rows; x++)
{
cout.width(5);
cout << ELEITORAL[x][y];
}
cout << endl;
}
cout << endl;
}
void fill(double **p, int rowsize, int colsize) {
std::cout << std::fixed;
std::cout << std::setprecision(1);
printf("\n Introduza o n%cmero de votos nas listas por ordem \n", 163);
for (int col = 0; col < colsize; col++)
{
cin >> p[row][col];
}
cout << endl;
for (int row = 1; row < rowsize; row++)
{
for (int col = 0; col < colsize; col++)
{
p[row][col] = (p[0][col]/(row + 1));
}
cout << endl; //preenche as linhas
}
}//FILL OUT THE ARRAY
void print(double **p, int rowsize, int colsize)
{
for (int i = 0; i < header.size(); i++) { //HEADER IS TO STORE THE
//NAMES OF THE POLITICAL PARTIES
cout << setw(9) << header[i] << " ";
}
cout << endl;
for (row = 0; row < rowsize; row++) //IMPRIME A MATRIZ EM SI
{
for (col = 0; col < colsize; col++)
{
cout << setw(10) << p[row][col];
}
cout << endl;
}
}//PRINTS THE ARRAY
int MATRIZ()
{
std::cout << std::fixed;
std::cout << std::setprecision(1);
double rows, columns;
printf("\n Qual o n%cmero de candidatos a eleger? \n", 163);
cin >> rows;
printf("\n Qual o n%cmero de listas candidatas? \n", 163);
cin >> columns;
for (i = 0; i < columns; i++)
{
cout << " Qual o nome da lista " << i+1;
cout << endl;
cin >> nomL;
header.push_back(nomL);
}
cout << endl;
system("cls");
ELEITORAL = new double*[rows];
for (int row = 0; row < rows; row++)
{
ELEITORAL[row] = new double[columns];
}
fill(ELEITORAL, rows, columns);
cout << endl;
//After this I have a switch, in case 5 I call the functions
//giving me trouble
case '5':
{
bubble_sort(ELEITORAL);
DisplayTheArray(ELEITORAL);
break;
}
Your display function is sketchy as you assume that the array has MAX dimensions. So my bet would be that your program seg faults due to memory access violation. Please, don't use new, instead use a vector. You won't have to pass the length as a separate parameter and in this case you won't get it wrong. Also double is not appropriate type for indexing, turn on compiler warnings and fix them.
Here's a simple example how can vector be used to make a matrix:
#include <iostream>
#include <vector>
using row_t = std::vector<double>;
using matrix_t = std::vector<row_t>;
//matrix_t = std::vector<std::vector<double>>; Vector of vectors of double
//Pass by reference to avoid copy
//Pass by const if the matrix should be read-only
void printMatrix(const matrix_t& mat)
{
for(auto& row: mat)
for(auto& val: row)
std::cout<<val << ' ';
std::cout<<'\n';//Use this instead of endl if you want just a new line
}
void doubleMatrix(matrix_t& mat)
{
//If you need access to indices during iterating
for(std::size_t r = 0; r < mat.size();++r)
for(std::size_t c = 0; c < mat[r].size();++r)
mat[r][c] *=2.0;
}
int main()
{
std::size_t rows, columns;
std::cin >> rows;
std::cin >> columns;
double fill_value = 0.0;
matrix_t matrix(rows);
//Resize rows to given column width.
for(auto& row: matrix)
row.resize(columns, fill_value);
printMatrix(matrix);
doubleMatrix(matrix);
printMatrix(matrix);
}
Last thing I noticed, If you want to swap two values, use std::swap.
Related
the problem is
arange the columns of the array X (n, m) in ascending order.
I wrote such code in c ++ myself, but in the end it does not sort all the columns correctly. Please help if anyone knows.
#include <iostream>
using namespace std;
int main() {
int n, m;
cout << "array size: n = ";
cin >> n;
cout << "array size: m = ";
cin >> m;
int array[n][m];
int arrayS[n];
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
cout << array[y][i] << " ";
}
cout << endl; //endline
}
cout << "************************************\n";
cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
cout << arrayS[i] << " ";
}
}
First of all, we need to make your code compilable. You are using so called VLA (variable length arrays), like in int array[n][m];. Rhese VLAs are not part of the C++ language and will not compile. I replaced them with a std::vector which will work in the same way. Then I corrected the code identations (I edited also your question) and then it is possible to compile.
It will then lool like the below (but of course still not working)
#include <iostream>
#include <vector>
int main() {
int n, m;
std::cout << "array size: n = ";
std::cin >> n;
std::cout << "array size: m = ";
std::cin >> m;
std::vector<std::vector<int>> array(n, std::vector<int>(m, 0));
std::vector<int> arrayS(n);
for (int z = 0; z < n; z++) {
for (int a = 0; a < m; a++) {
std::cin >> array[z][a];
}
}
for (int i = 0; i < n; i++) {
arrayS[i] = array[i][0];
}
for (int y = 0; y < n; y++) {
for (int i = 0; i < m; i++) {
std::cout << array[y][i] << " ";
}
std::cout << std::endl; //endline
}
std::cout << "************************************\n";
std::cout << "massivin sutunlari\n";
int enk = 0;
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
enk = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = enk;
}
}
for (int i = 0; i < n; i++)
{
std::cout << arrayS[i] << " ";
}
}
Some basic hints. Please use "speaking" variable names and write many many comments, best, one than more comment per line of code. Then you would already see the problems by yourself.
You have some hard bugs in your code that will most likely crash you program. Where you thy to sort, you use the magic number 9 (for whatever reasons) and so go out of bounds of the define arrays.
Additionally, your implementation of bubble sort is wrong. You may check many many examples in the net.
Then, you do only sort one column. You need to implement a bubble sort for each column of your matrix.
As a next step I will use better variable names and write comments. The code will still not work. But see and understand the difference.
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
for (int i = 0; i < 9; i++)
for (int j = 0; j < 9; j++)
{
if (arrayS[j] > arrayS[j + 1])
{
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
Next, we fix the sorting for one column.
Only minor changes needed:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// We can store one column here
std::vector<int> arrayS(numberOfRows);
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Copy the first column in a separate array
for (int i = 0; i < numberOfRows; i++) {
arrayS[i] = array[i][0];
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Sorted first column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
for (int i = 0; i < numberOfRows-1; i++)
for (int j = 0; j < numberOfRows - 1; j++)
{
// If this value is bigger than the following value, then swap them
if (arrayS[j] > arrayS[j + 1])
{
// Swap
tempValue = arrayS[j];
arrayS[j] = arrayS[j + 1];
arrayS[j + 1] = tempValue;
}
}
// Show the result of the sorting
for (int i = 0; i < numberOfRows; i++)
{
std::cout << arrayS[i] << " ";
}
}
This works already. But, my gues is that all columns shall be sorted.
Then, finally, it would look like that:
#include <iostream>
#include <vector>
int main() {
// Here we will define the dimensions for our matrix
int numberOfRows{}, numberOfColumns{};
// Inform user what to do. Enter number of rows of the matrix
std::cout << "\nPlease enter the number of rows: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfRows;
// Inform user what to do. Enter number of columns of the matrix
std::cout << "\nPlease enter the number of columns: ";
// Read the number of rows from the user via std::cin
std::cin >> numberOfColumns;
// Define the array for the complete 2d matrix
std::vector<std::vector<int>> array(numberOfRows, std::vector<int>(numberOfColumns, 0));
// Inform user what to do. Enter all data for the matrix
std::cout << "\nPlease enter all data for the matrix\n";
// Now read all data, for all rows and columns from the user, via std::cin
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cin >> array[row][col];
}
}
// Show current data in our matrix
std::cout << "\n\nThe matrix:\n\n";
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
// SHow some status message
std::cout << "\n\n\n************************************\n";
std::cout << "Matrix with sorted column\n";
// This is a temporary variable needed to swap 2 values
int tempValue = 0;
// Try to do bubble sort
// Go over all entries-1 in the column array.
// And compare the current value with the next value
// Do for all columns
for (int col = 0; col < numberOfColumns; ++col)
for (int i = 0; i < numberOfRows-1; ++i)
for (int row = 0; row < numberOfRows - 1; ++row)
{
// If this value is bigger than the following value, then swap them
if (array[row][col] > array[row + 1][col])
{
// Swap
tempValue = array[row][col];
array[row][col] = array[row + 1][col];
array[row + 1][col] = tempValue;
}
}
// Show the result of the sorting
for (int row = 0; row < numberOfRows; ++row) {
for (int col = 0; col < numberOfColumns; ++col) {
std::cout << array[row][col] << " ";
}
std::cout << '\n'; //endline
}
}
I'm writing a program to find the determinant of a matrix n x n, using Laplace expansion.
Briefly, the program creates a two-dimensional array based on a user request. The users choose the size of the two-dimensional array and fills it in themselves. Next comes the computation of the matrix using Laplace.
The problem is that I can't use the resulting array values in the determinant function. I'm completely new to C ++, so any help would be welcome. The code shown below. Thanks
#include<iostream>
#include<iomanip>
#include<math.h>
using namespace std;
void fin(int**, int, int);
void fout(int**, int, int);
int main() {
int **board, n;
double alpha, beta;
cout << "Enter the number of rows and columns: ";
cin >> n;
cout << endl;
board = new int* [n];
for(int row = 0; row < n; row++)
board[row] = new int[n];
fin(board,n,n);
cout << endl;
fout(board,n,n);
cout << endl;
cout << "Determinant of the matrix is " << determinant(board, n);
cout << endl;
return 0;
}
void fin(int **p, int R, int C)
{
for(int row = 0; row < R; row++)
{
cout << "Enter " << C + 1 << " numbers for row number " << R + 1 << ": ";
for(int col = 0; col < C; col++)
cin >> p[row][col];
cout << endl;
}
}
void fout(int **p, int R, int C)
{
for(int row = 0; row < R; row++)
{
for(int col = 0; col < C; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
int determinant( int **result, int n) {
int det = 0;
int submatrix[10][10];
if (n == 2)
return ((result[0][0] * result[1][1]) - (result[1][0] * result[0][1]));
else {
for (int x = 0; x < n; x++) {
int subi = 0;
for (int i = 1; i < n; i++) {
int subj = 0;
for (int j = 0; j < n; j++) {
if (j == x)
continue;
submatrix[subi][subj] = result[i][j];
subj++;
}
subi++;
}
det = det + (pow(-1, x) * result[0][x] * determinant( submatrix, n - 1 ));
}
}
return det;
}
I have a problem with my homework that asks me to have the compiler print out a matrix in which all the diagonals are outputted as zero. I also have to pass it to a function. However, I have no idea how to do this..
Here is my code:
#include <iostream>
using namespace std;
int diagonals();
int main()
{
//problem 1
int matrix[3][3];
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3 ; j++)
{
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
for (int i = 1; i <= 3; i++)
{
for (int j = 1; j <= 3; j++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}
cout << "\nReverse of the matrix:" << endl;
for (int j = 1; j <= 3; j++)
{
for (int i = 1; i <= 3; i++)
{
cout << matrix[i][j] << " ";
}
cout << endl;
}//end of problem 1
//problem 2
cout << "Diagonals changed to 0:\n" << endl;
}
your matrix declaration says int matrix[3][3]; that it has three 1-D array & in each 1-D array you can store three elements. And in C/C++ array index starts from zero.
Problematic statement is for (int i = 1; i <= 3; i++) as you are skipping matrix[0][0] and trying to store into matrix[3][3] which doesn't exist which in turn causes undefined behavior.
So firstly start iterating loop from 0 to number of rows & column respectively.
for (int i = 0; i < 3; i++) {
for (int j = 0; j < 3 ; j++) {
cout << "Row " << i << " column " << j<< ": ";
cin >> matrix[i][j];
}
}
Coming to task you mentioned, print out a matrix in which all the diagonals are outputted as zero. ? write one condition so that if row value & col value are equal then assign it to zero otherwise scan from user. Here is the sample code
int main(void) {
int matrix[3][3] = { 0 }; /* initialize it */
int row = sizeof(matrix)/sizeof(matrix[0]); /* find no of rows */
int col = sizeof(matrix[0])/sizeof(matrix[0][0]);/* find no of columns */
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
if( i == j)
matrix[i][j] = 0;/* when i and j are equal means thats diagonal and assign it to zero */
else /* if its not diagonal then scan from user */
std::cin>>matrix[i][j];
}
}
return 0;
}
Secondly, I also have to pass it to a function. for this learn how to pass 2d array to a function. Here is the sample example.
void diagonal(int (*mat)[3],int row, int col) { /* mat is pointer to an array */
std::cout<<"printing matrix "<<std::endl;
for (int i = 0; i < row; i++) {
for (int j = 0; j < col; j++) {
std::cout<<mat[i][j]<<"\t";
}
std::cout<<std::endl;
}
}
And call diagonal() like below from main() function as
diagonal(matrix,row,col); /* pass matrix, no of rows, no of columns */
I am trying to sort a two dimensional dynamic array when row 1 is for product ID and row 2 is for the product price. I want to sort by product ID, and have the results displayed formatted with width of 5. Here is my code:
This section is fine and does what I am looking for:
void readData (int**, int, int);
void printData(int**, int, int);
void sortbyPartID(int**, int, int);
int main()
{
int index;
int **PriceSheet, rows, columns;
cout << "Enter the number of Products, and then the number of values associated with the products: ";
cout << "For default values, enter 5 (FIVE ITEMS, and enter 2 (TWO Values: ID and PRICE). ";
cin >> columns >> rows;
cout << endl;
PriceSheet = new int* [rows];
for (int row = 0; row < rows; row++)
PriceSheet [row] = new int[columns];
readData (PriceSheet, rows, columns);
cout << endl;
printData(PriceSheet, rows, columns);
sortbyPartID(PriceSheet, rows, columns);
return 0;
}
void readData (int **p, int rowSize, int colSize)
{
for (int row = 0; row < rowSize; row++)
{
cout << "Row ZERO is the Product ID and Row 1 is the Product Price\n";
cout << "Enter " << colSize << " numbers for the row number " << row << ": ";
for (int col = 0; col < colSize; col++)
cin >> p[row][col];
cout << endl;
}
}
void printData (int **p, int rowSize, int colSize)
{
cout << "\n\nThese are the Products IDs and Prices as entered in the system:\n";
for (int row = 0; row < rowSize; row++)
{
for (int col = 0; col < colSize; col++)
cout << setw(5) << p[row][col];
cout << endl;
}
}
THIS SECTION IS WHERE I NEED HELP
It reads correctly and prints the unsorted array also correctly, but I cannot figure out a way to sort the array. Specifically speaking, I need help on the void sortbyPartID function. I would like to use bubble sort, and I cannot figure out how to get this function to work. Any help with the sorting function/algorithm would be greatly appreciated.
void sortbyPartID (int **p, int rowSize, int colSize)
{
int swap = -1;
int end = colSize;
int sortedID = **p;
cout << "\n\nThese are the Products sorted Products IDs:\n";
for (int counter = colSize -1; counter >= 0; counter --)
for (int index = 0; index < end ; index ++)
{
if (sortedID[index] > sortedID[index + 1])
{
swap = *sortedID[index + 1];
sortedID[index + 1] = sortedID[index];
*sortedID[index] = swap;
}
}
for(int index = 0; index < end; index++)
{
cout << sortedID[index] << ", ";
}
cout << endl;
end --;
}
When I run, I get some weird results on the last section. Maybe I am missing something simple, not sure.
We can also perform this using do-while as follows:
bool isSwaped;
do
{
isSwaped = false;
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
int swap = p[index + 1][0];
p[index + 1][0] = p[index][0];
p[index][0] = swap;
isSwaped = true;
}
}
} while (isSwaped);
You can simplify the entire thing by using objects. Objects allow you to handle the related data in a sane fashion. Also highly recommend are vectors instead of C arrays.
struct Product {
int id;
int price;
vector<int> others;
}
You can then store your products in vector<Product> my_products; and then sorting everything with
std::sort(my_products.begin(), my_products.end(),
[](const Product& a, const Product& b) { return a.id < b.id; });
You can keep the existing input/output format, but place the values in the right place. This way it's almost impossible to mess up the attributes and everything is easy to work with.
int sortedID = **p; is not what you want, and should be removed. (I think you wanted int** sortedID = p;)
Your bubble-sort should be something like:
for (int counter = colSize -1; counter >= 0; --counter)
{
for (int index = 0; index < end - 1 ; ++index)
{
if (p[index][0] > p[index + 1][0])
{
// std::swap(p[index], p[index + 1]);
int* swap = p[index + 1];
p[index + 1] = p[index];
p[index] = swap;
}
}
}
Live Demo
I was trying to find the code for finding the determinant of a square matrix , and I came across this code.
int det(vector<vector<int> > mat) {
int n = mat.size();
for(int col = 0; col < n; ++col) {
bool found = false;
for(int row = col; row < n; ++row) {
if(mat[row][col]) {
mat[row].swap(mat[col]);
found = true;
break;
}
}
if(!found) {
return 0;
}
for(int row = col + 1; row < n; ++row) {
while(true) {
int del = mat[row][col] / mat[col][col];
for (int j = col; j < n; ++j) {
mat[row][j] -= del * mat[col][j];
}
if (mat[row][col] == 0)
break;
else
mat[row].swap(mat[col]);
}
}
}
li res = 1;
for(int i = 0; i < n; ++i) {
res *= mat[i][i];
}
return abs(res);
}
But I am having trouble understanding line 20-29 i.e where the subtraction of row from multiple of another row is performed. I mean why the while loop is required here ? as I am
subtracting the quotient*dividend , It should always be 0 , right ? So I think it should be just one iteration. So , why we need to perform this mat[row].swap(mat[col]); operation ?
Thanks in advance.
There is some strange logic in your code to account for the fact that you are performing your calculations using integer arithmetic.
Say you have a 3x3 matrix in which the first two rows are:
4 6 5
1 2 3
When you compute del for col=0 and row=1, you will get:
del = 1/4 = 0
With that, when you compute:
mat[row][j] -= del * mat[col][j];
mat[row][j] doesn't change at all.
To account for that, you swap the rows. Now the first two rows are:
1 2 3
4 6 5
With the rows swapped like that, the value of del is 4/1 = 4. Now the line:
mat[row][j] -= del * mat[col][j];
does make a difference. The value of mat[1][0] ends up being zero, which is what you need. So you break out of the while loop.
Here's an instrumented version of your function that produces a lot of debug output, with a helper function to print the matrix and the main function to test the code.
#include <iostream>
#include <vector>
#include <stdlib.h>
using namespace std;
void printMatrix(vector<vector<int> > const& mat)
{
int n = mat.size();
for(int row = 0; row < n; ++row) {
for(int col = 0; col < n; ++col) {
cout << mat[row][col] << " ";
}
cout << "\n";
}
cout << "\n";
}
int det(vector<vector<int> > mat) {
int n = mat.size();
for(int col = 0; col < n; ++col) {
cout << "Column: " << col << "\n";
printMatrix(mat);
bool found = false;
for(int row = col; row < n; ++row) {
if(mat[row][col]) {
cout << "Got non-zero value for row " << row << " and col " << col << "\n";
if ( row != col )
{
cout << "(1) Swapping rows " << col << " and " << row << "\n";
mat[row].swap(mat[col]);
printMatrix(mat);
}
else
{
cout << "Not swapping rows\n";
}
found = true;
break;
}
}
if(!found) {
cout << "Did not find a non-zero row. Column: " << col << "\n";
return 0;
}
for(int row = col + 1; row < n; ++row) {
while(true) {
int del = mat[row][col] / mat[col][col];
cout << "del: " << del << "\n";
for (int j = col; j < n; ++j) {
mat[row][j] -= del * mat[col][j];
}
if (mat[row][col] == 0)
{
break;
}
else
{
cout << "(2) Swapping rows " << col << " and " << row << "\n";
mat[row].swap(mat[col]);
printMatrix(mat);
}
}
}
}
printMatrix(mat);
long res = 1;
for(int i = 0; i < n; ++i) {
res *= mat[i][i];
}
return abs(res);
}
int main()
{
vector<vector<int> > mat = { {4, 6, 5}, {1, 2, 3}, {8, 10, 9} };
int r = det(mat);
cout << "Determinant: " << r << endl;
return 0;
}