int Pascal_Tri(int row , int col)
{
if (row==col || col==0)
return 1 ;
else
{
return Pascal_Tri(row-1,col)+Pascal_Tri(row-1,col-1);
}
}
there is a problem with this code and I can not discover it.
when I run it, the program stops working and no results disappear
C++11
#include <iostream>
#include <vector>
std::vector<int> pascal(int height, std::vector<int> curr)
{
for(int i=0; i<curr.size(); i++)
std::cout<<curr[i]<<" ";
std::cout<<std::endl;
if(height<=0)
return curr;
std::vector<int> newCurr(curr.size()+1,1);
for(int i=0; i+1 < curr.size(); i++)
newCurr[i+1] = curr[i] + curr[i+1];
return pascal(height-1,newCurr);
}
int main()
{
int row, col;
std::cin>>row>>col;
std::vector<int> rowPascal = pascal(row,std::vector<int>{1});
std::cout<< rowPascal[col];
}
With the driver function to test. I know it's not very efficient but it should do!
This will basically give you the number at a specific row ( from the top) and a specific col (from the left) in the pascal's triangle . (both zero indexed)
Given that it's unreasonably difficult to print the triangle without using loops, here is a solution that uses your purely recursive Pascal_Tri function to compute the numbers but prints them with a loop:
int rowsToPrint = 5;
for (int row = 0; row < rowsToPrint; ++row)
{
for (int col = 0; col <= row; ++col)
std::cout << Pascal_Tri(row, col) << ", ";
std::cout << std::endl;
}
Demo
Related
#include <bits/stdc++.h>
using namespace std;
const int MAX = 100;
//Function to calculate largest column
void largestInColumn(int mat[][MAX], int rows, int cols)
{
for (int i = 0; i < cols; i++) {
// initialize the maximum element with 0
int maxm = mat[0][i];
// Run the inner loop for rows
for (int j = 1; j < rows; j++) {
// check if any element is greater than the maximum element of the column and replace it
if (mat[j][i] > maxm)
maxm = mat[j][i];
}
cout << maxm << endl;
}
}
// Driver code
int main()
{
int n , m ;
cin>>n>>m;
int mat[n][m];
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
cin>>mat[i][j];
}
}
largestInColumn(mat, n, m);
return 0;
}
I will answer the question using valid C++ statements. There are no VLAs in C++. I will use a std::vector instead.
There is also no need to store any value of the matrix for this task. You can make the decision already during reading of the values.
#include <iostream>
#include <vector>
#include <limits>
int main() {
// Read number of rows and columns
if (size_t numberOfRows{}, numberOfColumns{}; std::cin >> numberOfRows >> numberOfColumns) {
// Here we will store the max values per column, so, the result
std::vector<int> maxColumnValue(numberOfColumns, std::numeric_limits<int>::lowest());
// Read all rows and columns
for (size_t row{}; row < numberOfRows; ++row)
for (size_t col{}; col < numberOfColumns; ++col)
// If the current value of the column is greater than the current max value, then use new value instead
if (int value{ std::numeric_limits<int>::lowest() }; std::cin >> value)
if (value > maxColumnValue[col]) maxColumnValue[col] = value;
// Show result to the user
for (const int m : maxColumnValue) std::cout << m << '\n';
}
return 0;
}
The cause of the error is due to you trying to pass a variable-length-array to a function that requires a standard 2D array.
First, variable-length-arrays (VLA's) are not part of standard C++. Arrays in C++ require that the sizes of the array are known at compile-time, not runtime. So pretend they don't exist, because technically, they do not exist in standard C++.
Thus you have two choices:
Declare a non-variable-size 2D array and use that, or
Use a container that is built to have dynamic size, such as std::vector.
Since you did not specify how large n could be, then solution 2 is safer.
Given that, here is your code using std::vector:
#include <vector>
#include <iostream>
using Int1D = std::vector<int>;
using Int2D = std::vector<Int1D>;
//Function to calculate largest column
void largestInColumn(Int2D& mat, int rows, int cols)
{
for (int i = 0; i < cols; i++)
{
int maxm = mat[0][i];
for (int j = 1; j < rows; j++)
{
if (mat[j][i] > maxm)
maxm = mat[j][i];
}
std::cout << maxm << std::endl;
}
}
int main()
{
int n , m ;
std::cin >> n >> m;
Int2D mat(n, Int1D(m));
for(int i=0;i<n;i++)
{
for(int j=0;j<m;j++)
{
std::cin >> mat[i][j];
}
}
largestInColumn(mat, n, m);
}
Using the input:
3 3
1 2 3
1 4 9
76 34 21
The output is:
76
34
21
I tried to multiply a vector by a matrix but I can't get it to work because the loop always stops at one line. But with no error code, I've tried different ways to write the code into the resulting vector but it doesn't work. The outputs are to control where the loop stops, it stops after res[i] += (A[i][k] * B[k]);.
This is the specific function to perform the vector & matrix multiplication, if you need all the code let me know.
void vector_matrix_multiplication(vector<vector<int>> A,vector<int> B, int col1, int row1, int row2, vector<int>& res) {
int row = row1;
if(row1 < row2)
row = row2;
for(int i = 0; i < row; i++) {
cout << "Loop 1 ";
cout << i << endl;
for (int k = 0; k < col1; k++) {
cout << "Loop 2 " << i << " " << k << endl;
res[i] += (A[i][k] * B[k]);
cout << "Loop 2?" << endl;
}
}
The output of the function (with input A = {{2,3},{4,5}} & B = {1,2} is:
Loop 1 0
Loop 2 0 0
#include <iostream>
#include <vector>
using namespace std;
void vectorinput(vector<int>& a, int col){
cout << "Vector: " << endl;
for(int i = 0; i < col; i++) {
int x;
cin >> x;
a.push_back(x);
}
}
void matrixinput(vector<vector<int>>& a, int row, int col){
cout << "Matrix: " << endl;
for(int i = 0; i < row; i++) {
vector<int> vector;
for(int j = 0; j < col; j++) {
int x;
cin >> x;
vector.push_back(x);
}
a.push_back(vector);
}
}
int main(){
vector<int> vector;
vector<vector<int>> matrix; //Matrix is read in separate function
int row1 = 0; //Number of rows of first matrix
int col1 = 0; //Number of columns of first matrix
int row2 = 0; //Number of rows second matrix (redundant in this case)
int col2 = 0; //Number of columns second matrix
matrixinput(matrix1, row1, col1);
vectorinput(vector2, col2);
int row = row1; //Matrix with number of columns "col1", rows "row" - in this case both are 2
if(row2 > row1)
row = row2; //Vector with number of rows "row2" - in this case 2
vector<int> resvector(row, col1);
vector_matrix_multiplication(matrix2, vector1, col2, row, col1, resvector);
for(int i = 0; i < row; i++) {
cout << resvector[i] << endl;
}
return 0;
}
I hope this clarifies the purpose of the program and the function. I tried to cut it down a little because I have a lot of useless code in it. (Plus I struggled to input the code at first, was not quite sure how the code block works - sorry ^^)
There are following three bugs in your code:
Since you use the following ctor of std::vector
explicit vector(size_type count,
const T& value = T(),
const Allocator& alloc = Allocator());
, the second argument of resvector must be zero.
row1, row2, col1 and col2 are all zero through the main function and thus the loop in vector_matrix_multiplication does not work.
We can also reduce these variables to row and col of the matrix as #n.m. suggests in the comments.
matrix1, matrix2, vector1 and vector2 are not defined.
In summary, the following minimally fixed version will work fine for you:
int main()
{
std::vector<int> vec;
std::vector<std::vector<int>> mat;
int row = 2; //Number of rows of matrix
int col = 2; //Number of columns of matrix
matrixinput(mat, row, col);
vectorinput(vec, col);
std::vector<int> resvector(row, 0);
// 5th argument is redundant as #n.m. suggested
vector_matrix_multiplication(mat, vec, col, row, col, resvector);
for(int i = 0; i < row; i++) {
std::cout << resvector[i] << std::endl;
}
return 0;
}
and welcome to StackOverflow! I suggest you using mathematical libraries for this kind of stuff. The reason is:
they are already tested by someone else
they are efficient and optimized to use advanced CPU features
they are easier to use
I've used two different libraries: glm and Eigen
If you want to build your own library for learning purpose I suggest you looking how these libraries are written (they're open source)
I started doing Branch and Bound Algorithm for assignment problem in C++ and i can't find the right solution. First of all assignment problem example:
Assignment problem
Ok so each person can be assigned to one job, and the idea is to assign each job to one of the person so that all the jobs are done in the quickest way.
Here is my code so far:
#include "Matrix.h"
// Program to solve Job Assignment problem
// using Branch and Bound
#include <limits.h>
#include <vector>
#include <algorithm>
using namespace std;
template<class T>
NUM getCost(Matrix& matrix, size_t x, size_t y, vector<bool>& colUsed);
void run(Matrix& matrix, vector<size_t>& assignedJobs);
int main()
{
Matrix matrix;
matrix.setMatrix(N);
matrix.print();
vector<size_t> assignedJobs;
run(matrix, assignedJobs);
cout << assignedJobs[0];
/*
cout << "size:E " << v.size() << endl;
for (vector<NUM>::iterator i = v.begin(); i != v.end(); i++)
{
cout << *i << endl;
}
*/
return 0;
}
// remember to use x only LOCALLY!!!
NUM getCost(Matrix& matrix, size_t x, size_t y, vector<bool>& colUsed)
{
// pathCost
NUM pathCost = matrix.matrix[x++][y];
for (size_t col = 0; col < matrix.size(); col++)
{
if (!colUsed.at(col))
{
NUM min =
#if defined NUM_INT
INT_MAX;
#endif
#if defined NUM_DBL
DBL_MAX;
#endif
size_t row = x;
for (; row < matrix.size(); row++)
{
if (min > matrix.matrix[row][col])
{
min = matrix.matrix[row][col];
}
}
pathCost += min;
}
}
return pathCost;
}
void run(Matrix& matrix, vector<size_t>& assignedJobs)
{
// array of used columns
vector<bool> colUsed;
for (size_t i = 0; i < matrix.size(); i++)
{
colUsed.push_back(false);
}
for (size_t row = 0; row < matrix.size(); row++)
{
size_t col = 0;
// bombona
while (colUsed.at(col++)); col--;
// choose the best job for the current worker
vector<NUM> jobs;
// get all the job costs from which to choose the smallest
// row++
jobs.push_back(getCost(matrix, col, row, colUsed));
// iterator at the position of the smallest element of jobs
vector<NUM>::iterator i_min = min_element(jobs.begin(), jobs.end());
// index of the smallest element in jobs
size_t index = (size_t)distance(jobs.begin(), i_min);
colUsed.at(index) = true;
assignedJobs.push_back(index);
}
}
I know i might be out of track. I didn't use lower bound in the beginning, i'm actually a little confused how this algorithm exactly works. So even step by step walktrough through the algorithm would be helpful.
I am trying to pass c-strings into a function and have a table 6x6 printed out. However my code keeps compiling with an error. A segmentation fault. I understand that a seg fault is when the program looks for something that isn't there. I'm not sure how to fix this or how to alter this even after much research. Any suggestions would very much be appreciated.
Here's my code:
#include <iostream>
using namespace std;
void fillarrays(int labs[][6]);
void printarrays(int labs[][6]);
int main()
{
int labs[6][6];
fillarrays(labs);
printarrays(labs);
return 0;
}
void fillarrays(int labs[][6])
{
for(int row = 0; row<=6; row ++)
{
for(int col=0; col<=6; col++)
{
labs[row][col] = row;
}
}
}
void printarrays(int labs[][6])
{
cout << "Labs: " << '\t' << '\t' << endl;;
for(int rows=0 ; rows<6; rows++)
{
for(int cols=0; cols<6; cols++)
{
cout << '\t' << labs[rows][cols] << " ";
}
cout << endl;
}
}
labs[6][6] is an array with 6 rows first one is [0] and last one is [5], the same for cols, so change <=6 to <6 in fillarrays.
for(int row = 0; row<6;row ++) {
for(int col=0; col<6; col++) {
labs[row][col] = row;
}
}
for(int row = 0; row<=6;row ++) {
for(int col=0; col<=6; col++) {
labs[row][col] = row;
}
}
Look closely here - this fills a 7x7 array (indices 0 to 6 for rows and columns). But the array is only 6x6, so you're trying to write outside teh bounds of the array.
This is a reasonably common mistake; change the <=s to <s.
I've looked up some websites but I couldn't find an answer to my problem.
Here's my code:
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 6;
int filling(void);
void printing(int[AS][AS]);
int forsorting(int[][AS], int);
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
Array[i][j] = filling();
}
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
for (int il = 0; il<AS; il++)
{
for (int elle = 0; elle<AS; elle++)
Array[il][elle] =forsorting(Array, funny);
printing(Array);
}
system("PAUSE");
return 0;
}
int filling(void)
{
int kira;
kira = rand() % 87 + 12;
return kira;
}
void printing(int Array[AS][AS])
{
int counter = 0;
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
{
cout << setw(5) << Array[i][j];
counter++;
if (counter%AS == 0)
cout << endl << endl;
}
}
}
int forsorting(int Array[AS][AS], int funny)
{
int c, tmp, x;
int dice = 0;
int Brray[AS*AS];
int timpa = 0;
int super = 0;
//Transofrming Array[][] into Brray[]
for (int i = 0; i < AS; i++)
{
for (int k = 0; k < AS; k++)
{
Brray[timpa] = Array[i][k];
timpa++;
}
}
//Bubble sorting in Brray[]
for (int passer = 1; passer <= AS-1; passer++)
{
for (int timon = 1; timon <= AS-1; timon++)
{
if (Brray[timpa]>Brray[timpa + 1])
{
super = Brray[timpa];
Brray[timpa] = Brray[timpa + 1];
Brray[timpa + 1] = super;
}
}
}
//Transforming Brray[] into Array[][]
for (int e = 0; e<AS; e++)
{
for (int d = 0; d<AS; d++)
{
Brray[dice] = Array[e][d];
dice++;
}
}
***There's a part missing here***
}
What I have to do is, write a program using 3 functions.
The 1st function would fill my 2D array randomly (no problem with this part)
the 2nd function would print the unsorted array on the screen (no problem with this part)
and the 3rd function would sort my array diagonally as shown in this picture:
Then I need to call the 2nd function to print the sorted array. My problem is with the 3rd function I turned my 2D array into a 1D array and sorted it using Bubble sorting, but what I can't do is turn it back into a 2D array diagonaly sorted.
If you can convert from a 2D array to a 1D array, then converting back is the reverse process. Take the same loop and change around the assignment.
However in your case the conversion itself is wrong. It should take indexes in the order (0;0), (0;1), (1;0). But what it does is take indexes in the order (0;0), (0;1), (1;1).
My suggestion is to use the fact that the sum of the X and Y coordinates on each diagonal is the same and it goes from 0 to AS*2-2.
Then with another loop you can check for all possible valid x/y combinations. Something like this:
for ( int sum = 0; sum < AS*2-1; sum++ )
{
for ( int y = sum >= AS ? sum-AS+1 : 0; y < AS; y++ )
{
x = sum - y;
// Here assign either from Array to Brray or from Brray to Array
}
}
P.S. If you want to be really clever, I'm pretty sure that you can make a mathematical (non-iterative) function that converts from the index in Brray to an index-pair in Array, and vice-versa. Then you can apply the bubble-sort in place. But that's a bit more tricky than I'm willing to figure out right now. You might get extra credit for that though.
P.P.S. Realization next morning: you can use this approach to implement the bubble sort directly in the 2D array. No need for copying. Think of it this way: If you know a pair of (x;y) coordinates, you can easily figure out the next (x;y) coordinate on the list. So you can move forwards through the array from any point. That is all the the bubble sort needs anyway.
Suppose you have a 0-based 1-dimensional array A of n = m^2 elements. I'm going to tell you how to get an index into A, given and a pair of indices into a 2D array, according to your diagonalization method. I'll call i the (0-based) index in A, and x and y the (0-based) indices in the 2D array.
First, let's suppose we know x and y. All of the entries in the diagonal containing (x,y) have the same sum of their coordinates. Let sum = x + y. Before you got to the diagonal containing this entry, you iterated through sum earlier diagonals (check that this is right, due to zero-based indexing). The diagonal having sum k has a total of k + 1 entries. So, before getting to this diagonal, you iterated through 1 + 2 + ... + (sum - 1) entries. There is a formula for a sum of the form 1 + 2 + ... + N, namely N * (N + 1) / 2. So, before getting to this diagonal, you iterated through (sum - 1) * sum / 2 entries.
Now, before getting to the entry at (x,y), you went through a few entries in this very diagonal, didn't you? How many? Why, it's exactly y! You start at the top entry and go down one at a time. So, the entry at (x,y) is the ((sum - 1) * sum / 2 + y + 1)th entry, but the array is zero-based too, so we need to subtract one. So, we get the formula:
i = (sum - 1) * sum / 2 + y = (x + y - 1) * (x + y) / 2 + y
To go backward, we want to start with i, and figure out the (x,y) pair in the 2D array where the element A[i] goes. Because we are solving for two variables (x and y) starting with one (just i) and a constraint, it is trickier to write down a closed formula. In fact I'm not convinced that a closed form is possible, and certainly not without some floors, etc. I began trying to find one and gave up! Good luck!
It's probably correct and easier to just generate the (x,y) pairs iteratively as you increment i, keeping in mind that the sums of coordinate pairs are constant within one of your diagonals.
Store the "diagonally sorted" numbers into an array and use this to display your sorted array. For ease, assume 0-based indexing:
char order[] = { 0, 1, 3, 6, 10, 2, 4, 7, 11, 15, .. (etc)
Then loop over this array and display as
printf ("%d", Array[order[x]]);
Note that it is easier if your sorted Array is still one-dimensional at this step. You'd add the second dimension only when printing.
Following may help you:
#include <algorithm>
#include <iomanip>
#include <iostream>
#include <vector>
template<typename T>
class DiagArray
{
public:
DiagArray(int size) : width(size), data(size * size), orders(size * size)
{
buildTableOrder(size);
}
const T& operator() (int x, int y) const { return data[orders[width * y + x]]; }
T& operator() (int x, int y) { return data[orders[width * y + x]]; }
void sort() { std::sort(data.begin(), data.end()); }
void display() const {
int counter = 0;
for (auto index : orders) {
std::cout << std::setw(5) << data[index];
counter++;
if (counter % width == 0) {
std::cout << std::endl;
}
}
}
private:
void buildTableOrder(int size)
{
int diag = 0;
int x = 0;
int y = 0;
for (int i = 0; i != size * size; ++i) {
orders[y * size + x] = i;
++y;
--x;
if (x < 0 || y >= size) {
++diag;
x = std::min(diag, size - 1);
y = diag - x;
}
}
}
private:
int width;
std::vector<T> data;
std::vector<int> orders;
};
int main(int argc, char *argv[])
{
const int size = 5;
DiagArray<int> da(size);
for (int y = 0; y != size; ++y) {
for (int x = 0; x != size; ++x) {
da(x, y) = size * y + x;
}
}
da.display();
std::cout << std::endl;
da.sort();
da.display();
return 0;
}
Thank you for your assistance everyone, what you said was very useful to me. I actually was able to think about clearly and came up with a way to start filling the array based on your recommendation, but one problem now, Im pretty sure that my logic is 99% right but there's a flaw somewhere. After I run my code the 2nd array isnt printed on the screen. Any help with this?
#include "stdafx.h"
#include <iostream>
#include <math.h>
#include <time.h>
#include<iomanip>
#include<array>
#include <algorithm>
using namespace std;
const int AS = 5;
int filling(void);
void printing(int[AS][AS]);
int forsorting(int[][AS], int);
int main()
{
int funny = 0;
int timpa = 0;
int counter = 0;
int Array[AS][AS];
srand(time(0));
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
Array[i][j] = filling();
}
cout << "The unsorted array is" << endl << endl;
printing(Array);
cout << "The sorted array is" << endl << endl;
for (int il = 0; il<AS; il++)
{
for (int elle = 0; elle<AS; elle++)
Array[il][elle] =forsorting(Array, funny);
}
printing(Array);
system("PAUSE");
return 0;
}
int filling(void)
{
int kira;
kira = rand() % 87 + 12;
return kira;
}
void printing(int Array[AS][AS])
{
int counter = 0;
for (int i = 0; i<AS; i++)
{
for (int j = 0; j<AS; j++)
{
cout << setw(5) << Array[i][j];
counter++;
if (counter%AS == 0)
cout << endl << endl;
}
}
}
int forsorting(int Array[AS][AS], int funny)
{int n;
int real;
int dice = 0;
int Brray[AS*AS];
int timpa = 0;
int super = 0;
int median;
int row=0;
int col=AS-1;
//Transofrming Array[][] into Brray[]
for (int i = 0; i < AS; i++)
{
for (int k = 0; k < AS; k++)
{
Brray[timpa] = Array[i][k];
timpa++;
}
}
//Bubble sorting in Brray[]
for (int passer = 1; passer <= AS-1; passer++)
{
for (int timon = 1; timon <= AS-1; timon++)
{
if (Brray[timpa]>Brray[timpa + 1])
{
super = Brray[timpa];
Brray[timpa] = Brray[timpa + 1];
Brray[timpa + 1] = super;
}
}
}
//Transforming Brray[] into sorted Array[][]
for(int e=4;e>=0;e--)//e is the index of the diagonal we're working in
{
if(AS%2==0)
{median=0.5*(Brray[AS*AS/2]+Brray[AS*AS/2-1]);
//We start filling at median - Brray[AS*AS/2-1]
while(row<5 && col>=0)
{real=median-Brray[AS*AS/2-1];
Array[row][col]=Brray[real];
real++;
col--;
row++;}
}
else {
median=Brray[AS*AS/2];
//We start filling at Brray[AS*AS/2-AS/2]
while(row<5 && col>=0)
{real=Brray[AS*AS/2-AS/2];
n=Array[row][col]=Brray[real];
real++;
col--;
row++;}
}
}
return n;
}
Thanks again for your assistance