mtrix chain multiplication print the sequence of the mattrices - c++

I have written code for matrix chain multiplication in dynamic programming in c++.
there is an error in the recursive call for printing the correct parenthesization of the matrices. I am taking input from text file and giving output on a text file. please help..
#include <iostream>
#include <fstream>
#include <limits.h>
using namespace std;
int * MatrixChainOrder(int p[], int n)
{
static int m[100][100];
static int s[100][100];
int j, q;
int min = INT_MAX;
for (int i = 1; i <= n; i++)
m[i][i] = 0;
for (int L = 2; L <= n; L++) {
for (int i = 1; i <= n - L + 1; i++) {
j = i + L - 1;
m[i][j] = min;
for (int k = i; k <= j - 1; k++) {
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
return (*s);
}
void Print(int *s, int i, int j)
{
ofstream outfile("output.text");
if (i == j)
{
outfile << "a1";
}
else
outfile << "(";
{
Print(*s, i, s[i][j]);
Print(*s, s[i][j] + 1, j);
outfile << ")";
}
outfile.close();
}
int main()
{
int arr[100];
int num, i = 0;
ifstream infile("input.text");
while (infile)
{
infile >> num;
arr[i] = num;
i++;
}
i = i - 1;
infile.close();
Print(MatrixChainOrder(arr, i - 1), 0, i - 1);
return 0;
}

In C++ it is better to use std::vector for arrays. Aside from that, you can't mix pointers and arrays like that because the compiler loses track of array size.
For example this doesn't work:
int x[10][20];
void foo(int *ptr)
{
//the numbers 10 and 20 have not been passed through
}
But you can change it to
int x[10][20];
void foo(int arr[10][20])
{
//the numbers 10 and 20 are available
}
MatrixChainOrder is supposed to return a number, according to this link
int MatrixChainOrder(int s[100][100], int p[], int n)
{
int m[100][100];
for (int i = 0; i < 100; i++) m[i][i] = 0;
for (int i = 0; i < 100; i++) s[i][i] = 0;
int q = 0;
for (int L = 2; L <= n; L++) {
for (int i = 1; i <= n - L + 1; i++) {
int j = i + L - 1;
m[i][j] = INT_MAX;
for (int k = i; k <= j - 1; k++) {
q = m[i][k] + m[k + 1][j] + p[i - 1] * p[k] * p[j];
if (q < m[i][j]) {
m[i][j] = q;
s[i][j] = k;
}
}
}
}
return q;
}
int main()
{
int arr[] = { 40, 20, 30, 10, 30 };
int array_size = sizeof(arr) / sizeof(int);
int n = array_size - 1;
int s[100][100];
int minimum = MatrixChainOrder(s, arr, n);
printf("{ 40, 20, 30, 10, 30 } should result in 26000 : %d\n", minimum);
return 0;
}
Likewise you can change your Print function
void Print(int s[100][100], int i, int j)
{
if (i < 0 || i >= 100 || j < 0 || j >= 100)
{
cout << "array bound error\n";
}
//safely access s[i][j] ...
}

Related

Segmentation fault with cout in merge sort

I've read many posts but I can't figure out where is my error so I go with it.
My program throws the segfault at the cout<<endl. When I erase it, the program doesn't even print anything. It just prints the segfault. Aparently the program never reach to sort the vector.
#include <iostream>
#include <vector>
using namesapce std
void inserctionSort(std::vector<double> &v, int i, int j)
{
double temp;
for(i; i < v.size(); i++)
{
temp = v[i];
j = i - 1;
while((v[j] > temp) && (j >= 0))
{
v[j+1] = v[j];
j--;
}
v[j+1] = temp;
}
}
void merge_(std::vector<double> &v, int i, int k, int j)
{
std::vector<double> w(v.size());
int n = j - i + 1;
int p = i;
int q = k + 1;
for(int l = 0; l < n; l++)
{
if(p <= k && (q > j || v[p] <= v[q]))
{
w[l] = v[p];
p++;
}else
{
w[l] = v[q];
q++;
}
}
for(int l = 0; l < n; l++)
v[i - 1 + l] = w[l];
}
void mergeSort(std::vector<double> &v, int i, int j)
{
int n = j - i + 1, n0 = 3;
int k;
if(n <= n0)
{
inserctionSort(v,i,j);
}else
{
k = i - 1 + n / 2;
mergeSort(v, i, k);
mergeSort(v, k + 1, j);
merge_(v, i, k, j);
}
}
int main()
{
vector<double> v1 = {3.2,4.1,55.42,2.24,5.424,667.32,35.54};
cout<<"Vector desordenado: ";
for(int i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
cout<<"hola";
cout<<endl;
cout<<"hola";
mergeSort(v1, 0, v1.size()-1); //--> Core generado
//quickSort(v1, 0, v1.size()-1);
cout<<"Vector ordenado: ";
for(int i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
return 0;
}
You have problems in your code with vector indices assuming value -1 inside a couple of loops.
I have corrected these mistakes below, a working version of your code:
#include <iostream>
#include <vector>
using namespace std;
void inserctionSort(vector<double> &v, int i, int j)
{
int v_size = v.size();
double temp;
for (; i < v_size; i++) {
temp = v[i];
j = i - 1;
while ( (j >= 0) && (v[j] > temp) ) { // swapped conditions, as when j=-1, v[j]>temp is undefined
v[j+1] = v[j];
j--;
}
v[j+1] = temp;
}
}
void merge_(vector<double> &v, int i, int k, int j)
{
vector<double> w( v.size() );
int n = j - i + 1;
int p = i;
int q = k + 1;
for (int l = 0; l < n; l++) {
if ( p <= k && (q > j || v[p] <= v[q]) ) {
w[l] = v[p];
p++;
} else {
w[l] = v[q];
q++;
}
}
for(int l = 0; l < n; l++)
v[i + l] = w[l]; // deleted -1 from v[i - 1 + l], as it leads to v[-1] for i,l = 0
}
void mergeSort(vector<double> &v, int i, int j)
{
int n = j - i + 1, n0 = 3; // n = v.size()
int k;
if (n <= n0) {
inserctionSort(v,i,j);
} else {
k = i - 1 + n / 2;
mergeSort(v, i, k);
mergeSort(v, k + 1, j);
merge_(v, i, k, j);
}
}
int main()
{
vector<double> v1 = {3.2,4.1,55.42,2.24,5.424,667.32,35.54};
cout<<"Vector desordenado: ";
for (unsigned i = 0; i < v1.size(); i++)
cout<<v1[i]<<", ";
cout << "hola";
cout << endl;
cout << "hola";
mergeSort(v1, 0, v1.size()-1); //--> Core generado
//quickSort(v1, 0, v1.size()-1);
cout<<"Vector ordenado: ";
for (unsigned i = 0; i < v1.size(); i++)
cout << v1[i] << ", ";
return 0;
}

What's wrong in this solution to number of ways to generate change (Top Down)?

The famous coin change problem from hacker rank. It asks to compute a total number of ways to make a change for N using coins of given denominations.
For example, there are 5 ways to make a change for 10 using coins of denominations 2, 3, 4 and 5. They should be: {2,2,2,2,2}, {2,2,3,3}, {2,2,6}, {2,3,5} and {5,5}
I am unable to figure out a bug in my code:
#include <bits/stdc++.h>
using namespace std;
long getWays(int n, long c[], int m)
{
long dp[m + 1][n + 1];
for (long i = 0; i < m + 1; i++)
{
dp[i][0] = 1;
}
for (long k = 1; k < m + 1; k++)
{
for (long j = 0; j < n + 1; j++)
{
dp[k][j] = 0;
if (c[k - 1] <= j)
{
dp[k][j] = dp[k - 1][j] + dp[k][j - c[k - 1]];
}
else
{
dp[k][j] = dp[k - 1][j];
}
cout<<dp[k][j]<<" ";
}
cout<<endl;
}
return dp[m][n];
}
int main()
{
int n = 10;
long arr[] = {2, 5, 3, 6};
int m=4;
cout << getWays(n, arr, m) << endl;
return 0;
}
Corrected code:
#include <bits/stdc++.h>
using namespace std;
long getWays(int n, long c[], int m)
{
long dp[m + 1][n + 1];
for (long i = 0; i < m + 1; i++)
{
dp[i][0] = 1;
}
for (long i = 1; i < n + 1; i++)
{
dp[0][i] = 0;
}
for (long k = 1; k < m + 1; k++)
{
for (long j = 0; j < n + 1; j++)
{
if (c[k - 1] <= j)
{
dp[k][j] = dp[k - 1][j] + dp[k][j - c[k - 1]];
}
else
{
dp[k][j] = dp[k - 1][j];
}
}
}
return dp[m][n];
}
int main()
{
int n = 10;
long arr[] = {2, 5, 3, 6};
int m=4;
cout << getWays(n, arr, m) << endl;
return 0;
}

Errors Within Void Merge

I've been having problems trying to figure out how to fix this code I wrote for Mergesort.
The intended result was to output a sorted array of inputs, but the void merge function contains errors that result in either an unsorted array or an array of really large or small numbers.
I've tried many times to fix them, but the result still doesn't come out perfectly.
Can you look it over and tell me what I've been doing wrong?
#include "pch.h"
#include <iostream>
using namespace std;
void merge(int* arr, int p, int q, int r) {
//copy A[p.q] into L
//and A[q+1.r] into R
int i, j, k;
int n1 = q - p + 1;
int n2 = r - q;
int* L = new int[n1+1];
int* R = new int[n2+1];
for (i = 1; i <= n1; i++) {
L[i] = arr[p+i-1];
}
for (j = 1; j <= n2; j++){
R[j] = arr[q+j];
}
L[n1+1] = 99999;
R[n2+1] = 99999; //represents infinity
i = j = 1;
for (k = p; k <= r; k++)
{
if (L[i] <= R[j]) {
arr[k] = L[i];
i = i + 1;
}
else {
arr[k] = R[j];
j = j + 1;
}
return;
}
}
void mergesort(int* arr, int p, int r) {
if (p < r) {
int q = floor((p + r) / 2);
mergesort(arr, p, q);
mergesort(arr, q + 1, r);
merge(arr, p, q, r);
}
return;
}
int main() {
int r;
cin >> r;
int* arr = new int[r];
for (int i = 0; i < r; i++) {
int num;
cin >> num;
arr[i] = num;
}
int p = 0;
//sortint function
mergesort(arr,p,r);
for (int i = 0; i < r; i++) {
cout << arr[i] << ";";
}
return 0;
}

Designing MERGE-SORT Algorithm - VERY WEIRD ISSUE ! "std::bad_alloc at memory location 0x00486F78."

This is for an assignment in an algorithm class. I understand and agree that using a vector would simplify things, but that isn't an option.
The code for the Mergesort / merge algorithm can't be modified either.
I need to run the merge sort as follows:
starting from 100 all the way to 1000, increments of 100. For each increment I run it 5 times, for each of these times I run it 1000 times.
That being said - everything works fine until my loop reaches 700 and crashes with the error: "Unhandled exception at 0x75612F71 in msdebug.exe: Microsoft C++ exception: std::bad_alloc at memory location 0x010672F4."
Here is my code:
int const size = 6;
int const size2 = 1001;
int const times = 6;
int const interval = 11;
void merge(int arr[], int p, int q, int r)
{
int n1 = q - p + 1;
int n2 = r - q;
int * L = new int[n1 + 1];
int * R = new int[n2 + 1]; // line giving the error after 700
for (int i = 1; i <= n1; i++)
{
L[i] = arr[p + i - 1];
}
for (int j = 1; j <= n2; j++)
{
R[j] = arr[q + j];
}
L[n1 + 1] = 32768;
R[n2 + 1] = 32768;
int i, j;
i = j = 1;
for (int k = p; k <= r; k++)
{
if (L[i] <= R[j])
{
arr[k] = L[i];
i++;
}
else
{
arr[k] = R[j];
j++;
}
}
}
void mergeSort(int arr[], int p, int r)
{
int q;
if (p < r)
{
q = ((p + r) / 2);
mergeSort(arr, p, q);
mergeSort(arr, (q + 1), r);
merge(arr, p, q, r);
}
}
void copyArray(int original[][size2], int copy[], int row, int finish)
{
int i = 1;
while (i <= finish)
{
copy[i] = original[row][i];
i++;
}
}
void copyOneD(int orig[], int cop[])
{
for (int i = 1; i < size2; i++)
{
cop[i] = orig[i];
}
}
int main()
{
struct timeval;
clock_t start, end;
srand(time(NULL));
int arr[size][size2];
int arr2[size2];
int arrCopy[size2];
double tMergeSort[times][interval];
double avgTmergeSort[11];
/*for (int i = 1; i < (size2); i++)
{
arr2[i] = rand();
}*/
for (int i = 1; i < size; i++)
{
for (int j = 1; j < size2; j++)
{
arr[i][j] = rand();
}
}
for (int x = 100; x <= 1000; x = x + 100) //This loop crashes >=700
{
for (int r = 1; r <= 5; r++)
{
copyArray(arr, arr2, r, 1001);
for (int k = 0; k < 1000; k++)
{
copyOneD(arr2, arrCopy);
mergeSort(arrCopy, 1, x);
}
}
}
return 0;
}
You can ignore the code and the arrays. Those functions work fine.
Everything works fine until I set 'x <= 700' or higher and then it crashes.
I had a theory that maybe the computer runs out of memory for the pointers in the merge algorithm but when I tried to use delete it also crashed.
Any help is appreciated and suggestions as well.
Thanks

ERROR problem with a function. C++

In function Determininant i keep getting an error....
#include <iostream>
#include <fstream>
#include <cmath>
using namespace std;
const int maxsize = 10;
ifstream fin;
ofstream fout;
void transpose (double omatrix[][maxsize],double tmatrix [][maxsize], int array_size)
{
for(int i = 0; i < array_size; i++)
{
for(int j = 0; j < array_size; j++)
{
tmatrix[j][i] = omatrix[i][j];
}
}
}
void sub (double omatrix[][maxsize], double smatrix[][maxsize], int array_size, int i, int j)
{
int counter1 = 0, counter2 = 0;
for (int a = 0; a < array_size; a++)
{
if (a != i)
{
for (int b = 0; b < array_size; b++)
{
if (b != j)
{
smatrix[counter1][counter2] = omatrix[a][b];
counter2++;
}
}
counter1++;
}
}
}
double Determininant(double original_matrix[][maxsize], int array_size)
{
if(array_size == 1)
return original_matrix[0][0];
else if(array_size == 2)
return original_matrix[0][0] * original_matrix[1][1] - original_matrix[0][1] * original_matrix[1][0];
double d = 0.0;
double temp[maxsize][maxsize];
for(int i = 0; i < array_size; i++)
{
sub (original_matrix,temp,array_size, 0, i);
d += pow(-1.0,i) * original_matrix[0][i] * d(temp, array_size - 1);
}
return d;
}
void print (const double m[][maxsize], int array_size)
{
for(int i = 0; i < array_size; i++)
{
for(int j = 0; j < array_size; j++)
{
fout << m[i][j] << " ";
}
fout << "\n";
}
fout << "\n";
}
The error is error: 'd' cannot be used as a function.
Any ideas on whats wrong?
Exactly what the error message says: d is a double and you can't call it as a function. Perhaps you meant Determinant(temp, array_size - 1)?
It's the end of this line:
d += pow(-1.0,i) * original_matrix[0][i] * d(temp, array_size - 1);
As casablanca said, do you mean this?:
d += pow(-1.0,i) * original_matrix[0][i] * Determinant(temp, array_size - 1);
d += pow(-1.0,i) * original_matrix[0][i] * d(temp, array_size - 1);
The clause d(temp, array_size - 1) is telling C++ to call function d.