Matrix class: unknown problems in C++ - c++

My program compiles but has these problems:
It's not using the member function fill (now). When i got the fill function to work (a while ago), it didn't do adding, subtracting, and multiplication correctly because it didn't record the second matrix it was supposed to do those things with. I got it to work the way you see it now, but this is the result:
ubuntu:~/Desktop$ ./matrix
2
2
enter the matrix element by element(starting from the first row)
1
2
1
2
Segmentation fault (core dumped)
If someone can point out the mistakes, it would be greatly appreciated:
#include <iostream>
#include <cmath>
using namespace std;
class matrix
{
private:
int r;
int c;
double** arr;
double** arr2;
public:
matrix()
{
r = 1;
c = 1;
arr = 0;
arr2 = 0;
}
matrix(int rows, int columns)
{
r = row(r);
c = column(c);
arr = new double* [r];
for(int i =0; i<r; i++)
{
arr[i] = new double[c];
}
}
matrix(matrix& a)
{
r = a.row(r);
c = a.column(c);
arr = new double* [r];
for(int i =0; i<r; i++)
{
arr[i] = new double[c];
}
}
~matrix()
{
for( int i = 0 ; i < r ; i++ )
{
delete [] arr[i];
}
delete [] arr;
}
void copy()
{
arr2 = new double* [r];
for(int i =0; i<r; i++)
{
arr2[i] = new double[c];
}
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr2[i][j] = arr[i][j];
}
}
}
int row(int r)
{
return r;
}
int column(int c)
{
return c;
}
void fill(const int& r, const int& c)
{
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
cin>>arr[i][j];
}
}
}
void print()
{
for (int i=0; i < r; i++)
{
for (int j=0; j<c; j++)
{
cout<<arr[i][j]<<" ";
}
cout<<endl;
}
}
void sum()
{
double ** arr2 = arr;
cout << "enter the matrix you want to add" << endl;
fill(r, c);
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr[i][j] = (arr2[i][j] + arr[i][j]);
}
}
print();
}
void sub()
{
double ** arr2 = arr;
cout << "enter the matrix you want to subtract" << endl;
fill(r,c);
for (int i=0; i<r; i++)
{
for(int j=0; j<c; j++)
{
arr[i][j] = (arr2[i][j]) - (arr[i][j]);
}
}
print();
}
void multiplication()
{
double ** arr2 = arr;
cout << "enter the matrix you want to multiply by" << endl;
fill(r,c);
int k =0;
double ** arrm = arr;
for(int i=0;i< r;i++)
{
for(int j=0;j< c;j++)
{
arrm[i][j] = 0;
for(k=0;k< r;k++)
{
arrm[i][j] = arrm[i][j] + arr2[i][k] * arr[k][j];
}
}
}
print();
}
bool check(const int r, const int c)
{
if(r==c)
{return true;}
else
{return false;}
}
void get_det(const int r, const int c)
{
if(check(r,c) == true)
{
int n = r;
Determinant(arr,n);
cout <<"the determinant is: "<< endl;
}
else
{
cout << "can't" << endl;
}
}
double Determinant(double** arr, int n)
{
double det = 0;
double** m = NULL;
if (n == 1)
{ det = arr[0][0];}
else if (n == 2)
{
det = arr[0][0] * arr[1][1] - arr[1][0] * arr[0][1];
}
else if (n == 3)
{
det = arr[0][0]*(arr[1][1]*arr[2][2] - arr[1][2]*arr[2][1])
+ arr[0][1]*(arr[1][2]*arr[2][0] - arr[1][0]*arr[2][2])
+ arr[0][2]*(arr[1][0]*arr[2][1] - arr[1][1]*arr[2][0]);
}
else if (n > 3)
{
for (int j1=0;j1<n;j1++)
{
m = new double* [n-1];
for (int i=0;i<n-1;i++)
m[i] = new double[n-1];
for (int i=1;i<n;i++)
{
int j2 = 0;
for (int j=0;j<n;j++)
{
if (j == j1) continue;
m[i-1][j2] = arr[i][j];
j2++;
}
}
det += pow(-1,1+j1+1) * arr[0][j1] * Determinant(m,n-1);
for (int i=0;i<(n-1);i++)
delete m[i];
delete m;
}
}
return(det);
}
};
int main()
{
int r,c,answer;
cin >> r >> c;
matrix g(r,c);
cout << "enter the matrix element by element(starting from the first row)" << endl;
g.fill(r,c);
cout << "do you want add (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.sum();
}
else{}
cout << "do you want subtract (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.sub();
}
else{}
cout << "do you want multiply (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.multiplication();
}
else{}
cout << "do you want to know the determinant (1=yes / 0=no)" << endl;
cin >> answer;
if(answer == 1)
{
g.get_det(r,c);
}
else{}
return 0;
}

Related

Sequence Alignment problem using Pthreads

I am trying to implement Sequence alignment problem (Needleman-Wunsch algorithm) using p-Threads. I am confused how to map the concept of multi threading in this particular serial problem. The code of serial computation of sequence alignment is enclosed below.(Just Matrix calculation part)
#include<iostream>
#include<string.h>
#include<string>
#include<algorithm>
using namespace std;
class Matrix
{
private:
int x;
int y;
int** mat;
string gene1;
string gene2;
int match_penalty;
int mismatch_penalty;
int gap_penalty;
int minimum_penalty;
public:
Matrix(int gene1Len, int gene2Len)
{
x = gene2Len + 1; //gene2 length
y = gene1Len + 1; //gene 1 length;
mat = new int* [x];
for (int i = 0; i < x; i++)
mat[i] = new int[y];
for (int i = 0; i < x; ++i) {
for (int j = 0; j < y; ++j) {
mat[i][j] = 0;
}
}
//Default Penalties
match_penalty = 1;
mismatch_penalty = 3;
gap_penalty = 2;
minimum_penalty=0;
}
void Print_Matrix()
{
cout<<"\n";
for (int i = 0; i < x; i++)
{
for (int j = 0; j < y; j++)
{
cout << mat[i][j] << "\t";
}
cout << "\n";
}
}
void setGenes(string gene1, string gene2)
{
this->gene1 = gene1;
this->gene2 = gene2;
}
void setPenalty(int mismatch, int gp,int match)
{
mismatch_penalty = mismatch;
gap_penalty = gp;
match_penalty=match;
}
void setMatrix()
{
//1st row and 1st Column values
for (int i = 0; i < x; i++)
{
mat[i][0] = i * gap_penalty;
}
for (int i = 0; i < y; i++)
{
mat[0][i] = i * gap_penalty;
}
// Other matrix values
for (int i = 1; i < x; i++)
{
for (int j = 1; j < y; j++)
{
if (gene1[j - 1] == gene2[i - 1]) //Similar gene values (A==A ||T==T)
{
mat[i][j] = mat[i - 1][j - 1]+match_penalty;
}
else
{
mat[i][j] = max({ mat[i - 1][j - 1] + mismatch_penalty , mat[i - 1][j] + gap_penalty, mat[i][j - 1] + gap_penalty });
}
}
}
}
};
int main()
{
string gene1 = "ACCA";
string gene2 = "CCA";
int matchPenalty;
int misMatchPenalty ;
int gapPenalty ;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
Matrix dp(gene1.length(), gene2.length());
dp.setGenes(gene1, gene2);
dp.setPenalty(misMatchPenalty, gapPenalty,matchPenalty);
dp.setMatrix();
dp.Print_Matrix();
}
How can I implement the above problem in P-threads? So far, I have used two threads to calculate matrix values of 1st column and 1st row simultaneously.But I have no idea how to compute all values of matrix in parallel. Kindly see my source code:
#include<string>
#include<algorithm>
#include<iostream>
#include<string.h>
#include<pthread.h>
using namespace std;
//Global variables --shared by all threads
int matchPenalty;
int misMatchPenalty;
int gapPenalty;
struct gene_struct {
string gene1;
string gene2;
int rowSize;
int colSize;
int **mat;
};
void* set_matrix_row(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->rowSize; i++)
{
shared_block->mat[i][0] = i * gapPenalty;
}
return NULL;
}
void *set_matrix_column(void *args)
{
struct gene_struct *shared_block = (struct gene_struct *) args;
for (int i = 0; i < shared_block->colSize; i++)
{
shared_block->mat[0][i] = i * gapPenalty;
}
return NULL;
}
void set_Matrix_Diagnol(struct gene_struct shared_block)
{
//How Should I calculate rest of the matrix values using Pthreads?
}
void Print_Matrix(struct gene_struct shared_block)
{
cout<<"\n";
for (int i = 0; i < shared_block.rowSize; i++)
{
for (int j = 0; j < shared_block.colSize; j++)
{
cout << shared_block.mat[i][j] << "\t";
}
cout << "\n";
}
}
int main()
{
pthread_t ptid1, ptid2;
string gene1, gene2;
struct gene_struct shared_block;
cout << "Enter First Gene : ";
cin >> gene1;
cout << "Enter Second Gene : ";
cin >> gene2;
cout<<"Enter the value of Match Penalty" << endl;
cin >> matchPenalty;
cout<<"Enter the value of misMatchPenalty Penalty" << endl;
cin >> misMatchPenalty;
cout<<"Enter the value of gapPenalty Penalty" << endl;
cin >> gapPenalty;
shared_block.gene1 = gene1;
shared_block.gene2 = gene2;
shared_block.rowSize = gene2.length()+1;
shared_block.colSize = gene1.length()+1;
shared_block.mat = new int* [shared_block.rowSize]; //col = gene2+1
for (int i = 0; i < shared_block.rowSize; i++)
{
shared_block.mat[i] = new int[shared_block.colSize];
}
pthread_create(&ptid1, NULL, &set_matrix_row, (void *)&shared_block);
pthread_create(&ptid2, NULL ,&set_matrix_column, (void *)&shared_block);
pthread_join(ptid1,NULL);
pthread_join(ptid2,NULL);
Print_Matrix(shared_block);
}

Realize "-" operator overloading as a friend function of class

I try to realize difference of sets with "-". For example:
Set a = 1 2 3 4;
Set b = 3 4 5 6;
Set c = a - b; // (1 2);
How i should overload operator? I tried to use frienldy function, but it can't work with variable "size". Visual Studio show error "c2597" at 28th line (size++;)
I can't understand, how to overloading "-" for using it with two sets. When I overload method of class, i can use only one argument. When i use friend-function, i can use twi arguments (Set a, Set b), but i can't work with variable "size".
#include <iostream>
#include <locale.h>
#include <conio.h>
#include <vector>
using namespace std;
class Set {
private:
int size;
vector <int> vect;
public:
Set() { size = 0; }
~Set() { vect.clear(); }
void Enter();
void Show();
friend Set operator-(Set a, Set b)
{
size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
size++;
vect.push_back(a.vect[i]);
}
}
return a;
}
void add()
{
int element;
cout << "Введите новый элемент " << endl;
cin >> element;
size = size + 1;
vect.push_back(element);
}
};
void Set::Enter() {
cout << "Введите размер " << endl;
cin >> size;
vect.resize(size);
cout << "Введите элементы :" << endl;
for (int i = 0; i < size; i++)
{
cin >> vect[i];
}
}
void Set::Show() {
cout << "Множество: " << endl;
for (int i = 0; i < size; i++)
cout << vect[i] << " ";
cout << endl;
}
int main() {
setlocale(LC_ALL, "RUS");
Set a;
a.Enter();
Set b;
b.Enter();
Set c;
c = a - b;
c.Show();
c.add();
c.Show();
_getch();
return 0;
}
UPD:
I made it through method:
Set operator-(const Set& b)
{
Set a = *this;
Set tmp;
tmp.size = 0;
vect.clear();
int i, j, n = 0;
for (i = 0; i < a.size; i++) {
int cnt = 0;
for (j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
tmp.size++;
tmp.vect.push_back(a.vect[i]);
}
}
return tmp;
}
friend functions are not member methods, so you have to remove/replace usage of (implicit) this as size = 0, you might add extra object:
friend Set operator-(Set a, Set b)
{
Set res;
for (int i = 0; i < a.size; i++) {
int cnt = 0;
for (int j = 0; j < b.size; j++)
{
if (a.vect[i] == b.vect[j]) cnt++;
}
if (cnt == 0) {
res.size++;
res.vect.push_back(a.vect[i]);
}
}
return res;
}

fstream only reading integers

My code works fine when the file Im reading from only contains ints, but when I have floats in the file it doesnt seem to work, for example if I have 1.5 in the file it will only read it as 1 and it wont read any of the numbers after it.
Anyone knows whats causing this? The dynamic array where everything is saved in is a float so Im not sure what to do at this point
#include <iostream>
#include <fstream>
#include <string>
float *allocateArray(std::string fileName, int &arraySize, int &counter)
{
int a = 0;
std::ifstream myReadFile;
myReadFile.open(fileName);
float *arr = new float[arraySize]{0.0};
while (myReadFile >> a)
{
counter++;
if(counter == arraySize)
{
arr[arraySize -1] = a;
}
else
{
float *tempArray = new float[arraySize +1]{0.0};
for(int i = 0; i < arraySize; i++)
{
tempArray[i] = arr[i];
}
delete[] arr;
arraySize++;
arr = new float[arraySize];
for(int x = 0; x < arraySize; x++)
{
arr[x] = tempArray[x];
}
arr[arraySize-1] = a;
}
}
myReadFile.close();
return arr;
}
void output(float *arr, int arraySize,int counter)
{
float sum = 0.0;
for(int x = 0; x < arraySize; x++)
{
sum += arr[x];
}
float average = sum/counter;
std::cout << "Output: ";
for(int i = 0; i < arraySize; i++)
{
if(arr[i] > average)
{
std::cout << arr[i] << " ";
}
}
}
int main()
{
int arraySize = 1;
int counter = 0;
float *arr = allocateArray("input.in", arraySize, counter);
std::cout << "Input: ";
for(int x = 0; x < arraySize; x++)
{
std::cout << arr[x] << " ";
}
output(arr, arraySize, counter);
getchar();
return 0;
}

How to use function with parameters in class , c++?

I have to sum of two matrices (tridiagonal), everything works, but I don't know how to call function sum in main. I tried but it reports an error. Any help or recommendations would be appreciated.
.h:
class matrix
{
public:
matrix();
~matrix();
matrix(int i, int j);
void insert();
void iz();
void sum(matrix m1, matrix m2);
private:
int i;
int j;
vector<vector<int> > v;
};
.cpp
matrix::matrix()
{
}
matrix::matrix()
{
}
matrix::matrix(int i, int j){
v.resize(i);
for (int k = 0; k < i; k++)
v[k].resize(j);
this->i = i;
this->j = j;
}
void matrix::insert()
{
int x;
for (int a = 0; a < i; a++){
for (int b = 0; b < j; b++){
if (abs(a-b) <= 1){
x = rand() % 100+1;
v[a][b] = x;
}
else
v[a][b] = 0;
}
}
}
void matrix::iz()
{
for (int a = 0; a < i; a++){
for (int b = 0; b < j; b++)
cout << v[a][b] << " ";
cout << endl;
}
}
void matrix::sum(matrix m1, matrix m2)
{
matrix m3;
int c = m1.i;
int d = m1.j;
if (m1.i == m2.i && m1.j == m2.j)
{
for (int a = 0; a < c; a++)
{
for (int b = 0; b < d; b++){
m3.v[a][b] = m1.v[a][b] + m2.v[a][b];
}
cout << endl;
}
}
else
cout << "Error" << endl;
}
main
matrix m1(6, 6);
m1.insert();
m1.iz();
cout << endl << endl;
matrix m2(6, 6);
m2.insert();
m2.iz();
Here is the problem:
/*
matrix m3;
m3.sum(m1, m2);
m3.iz();
*/
cin.ignore();
cin.get();
return 0;
The problem lies in the sum function where you create a new object matrix m3, and perfor the addition on that object, instead of this.
Do: this->v[a][b] = m1.v[a][b] + m2.v[a][b];
instead of: m3.v[a][b] = m1.v[a][b] + m2.v[a][b];
Also, you need to set the this->i and this->j variables to m1.i and m1.j, plus you should also do all your resizing of this->v too.

Visual Studio Gives Ambiguous Error for No Real Reason

It gives the following error:
error C2872: 'count' : ambiguous symbol
Count variable has been declared as a global variable and the code compiles and runs in Sublime Text. Don't understand why Visual Studio is crying over it.
#include <iostream>
#include <fstream>
using namespace std;
int** am; // Adjacency matrix
int* ar, * ar2; // Arrays to work with
int n; // Number of nodes
int node1, node2, k; // For reading input from the console
int count;
bool checkReachability(int, int, int);
void fillArray(int);
void updateArray(int,int);
void freeMemory();
int main() {
ifstream in;
in.open("Input2.txt");
int a, b;
if(in.is_open()) {
in >> n;
// Allocate memory on the heap dynamically for the adjacency matrix:
am = new int*[n];
ar = new int[n];
ar2 = new int[n];
for (int i = 0; i < n; i++) {
am[i] = new int[n];
}
// Initialize the values of the adjacency matrix with 0s and the principle diagonal with 1s initially:
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
if (i == j) {
am[i][j] = 1;
} else {
am[i][j] = 0;
}
}
}
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
cout << "The adjacency matrix input is as follows: \n\n";
for (int i = 0; i < n; i++) {
for (int j = 0; j < n; j++) {
cout << am[i][j] << " ";
}
cout << endl << endl;
}
in.close();
} else {
cout << "\nError reading the input file\n\n";
}
char c;
do {
cout << "\nPlease enter the input (node1, node2, k): \n";
cin >> node1 >> node2 >> k;
fillArray(node1-1);
count = 0;
if(checkReachability(node1-1,node2-1,k)) {
cout << "\nReachable within " << k << " steps";
if (count < k) {
cout << " (actually " << count << ")";
}
cout << endl << endl;
} else {
cout << "\nNot reachable within " << k << " steps \n";
}
cout << "\nDo you want to continue? Y/N \n\n";
cin >> c;
} while (c == 'Y' || c == 'y');
freeMemory();
system("pause");
return 0;
}
bool checkReachability(int n1, int n2, int k) {
if (n1 == n2) return true;
count++;
if (count <= k) {
if (ar[n2] != 0) return true;
int x;
for (int i = 0; i < n; i++) {
if (ar[i] != 0 && i != n1) {
ar[i]++;
x = ar[i];
}
}
for(int i = 0; i < n; i++) {
ar2[i] = ar[i];
}
for(int i = 0; i < n; i++) {
if (ar2[i] == x) {
fillArray(i);
updateArray(x,i);
if (checkReachability(ar2[i], n2, k)) return true;
}
}
}
return false;
}
void fillArray(int x) {
// To fill the array with the adjacencies of a particular node
for(int i = 0; i < n; i++) {
ar[i] = am[x][i];
}
}
void updateArray(int x, int y) {
for(int i = 0; i < n; i++) {
if (ar[i] == 1 && i != y) {
ar[i] = x;
}
}
}
void freeMemory() {
// To free the dynamically allocated memory on the heap
for (int i = 0; i < n; i++) {
delete [] am[i];
}
delete [] ar;
delete [] ar2;
}
using namespace std is your problem.
Looks like the Microsoft implementation of either the iostream or fstream headers themselves include algorithm. This is causing the name clash with std::count().
So, as #Retiredninja suggested, if I choose to replace while(!in.eof()) with while(in >> a >> b) in:
while(!in.eof()) {
in >> a >> b;
am[a-1][b-1] = 1;
}
Does the rest of the code in the while loop remain the same or does it mean, the input has already been read into a and b when the condition is checked in while(in >> a >> b)?
And become the following:
while(in >> a >> b) {
am[a-1][b-1] = 1;
}
or does it remain:
while(in >> a >> b) {
in >> a >> b;
am[a-1][b-1] = 1;
}