C++: Pascal's triangle - weird results - c++

This is my first question so don't be mad at me, if I did something wrong.
I have to make a C++ program which returns an element from a selected row, for example:
Triangle 4 0 1 2 3
should return elements: 0, 1, 2 and 3 from row number 4, but it returns strange things, like:
Element 0: 1
Element 1: 10179988
Element 2: 50792126
Element 3: 91425820
I have no idea why
Here's my code:
#include <cstdlib>
#include <iostream>
#include <string>
#include <cstring>
using namespace std;
class Pascal {
private:
int *tab;
public:
Pascal(int n) throw(string) {
if (n < 0)
throw (string)"";
tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
};
int element(int m) {
return tab[m];
}
};
int main(int argc, char* argv[]) {
int n = 0, m = 0, elem = 0;
try {
n = strtol(argv[1], NULL, 0);
Pascal *row;
for(int i = 2; i < argc; i++) {
try {
m = strtol(argv[i], NULL, 0);
row = new Pascal(n+1);
if (m <= n && m >= 0) {
elem = row->element(m);
cout << "Element " << m << ": "<< elem << endl;
} else
cout << m << " - bad element index" << endl;
} catch (string ex) {
cout << argv[i] << " - bad element index!" << endl;
continue;
}
delete[] row;
}
} catch (string e) {
cout << argv[1] << " - bad row index!" << endl;
return 0;
}
}
I'll be grateful for any answer

tab = new int[n+1];
for(int i = 1; i <= n; i++) {
for(int k = i; k >=0; k--) {
if (k - 1 >= 0)
tab[k] += tab[k-1];
else
tab[k] = 1;
}
}
first iteration: i=1, k=1, tab[1]+=tab[0];
second iteration: i=1, k=2, tab[2]+=tab[1];
So you are not properly initializing your array, you are simply adding whatever values are in memory...
I think replacing if (k - 1 >= 0) with if (k - 1 > 0) should solve your problem

Try
tab = new int[n+1];
for(int i = 0; i <= n; i++) {
tab[i] = 1;
for(int k = i; --k > 0; )
tab[k] += tab[k-1];
}

Related

SelectionSort in c++ not sorting*

I am having a tough time trying to follow the logic here as to why it is not working correctly
expected output :
1 5 6 8
any help is greatly appreciated
Update: I got selection sort and insertion sort mixed up
OUTPUT:
unaltered array
5 8 1 6
1 -858993460 -858993460 6
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "SelectionSORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "SelectionSORT2\n";
}
cout << "SelectionSORT3\n";
}
#include <iostream>
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < 4; i++)
{
cout << array[i] << " ";
}
cout << endl;
}
UPDATE
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void SelectionSort(int *arr,int n)
{
cout << "Selection SORT1\n";
int I;
for (i = 0; i < n ; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = i;
int j;
for (j = i + 1;j < n ;j++)
{
std::cerr << j << ' ' << firstIndex << '\n';
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
swap(arr[i], arr[firstIndex]);
}
cout << " \n";
}
cout << " \n";
}
#include <iostream>
#include "BubbleSort.h"
#include "InsertionSort.h"
#include "SelectionSort.h"
using namespace std;
int main()
{
int array[] = { 5,8,1,6 };
int size = { sizeof(array) / sizeof(array[0]) };
cout << "unaltered array\n";
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
SelectionSort(array, size);
for (int i = 0; i < size; i++)
{
cout << array[I] << " ";
}
cout << endl;
unaltered array
5 8 1 6
SelectionSORT1
1 0
2 0
3 2
2 1
3 2
3 2
5 6 1 8
You are using the selection sort method not the insertion sort method.
Bit in any case the function is incorrect
void InsertionSort(int *arr,int n)
{
cout << "INSERTION SORT1\n";
int i;
for (i = 0; i < n - 2; i++) //-1 ||-2//
{
int firstIndex;
firstIndex = arr[i];
int j;
for (j = i + 1;j < n - 1;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
//cout << firstIndex;
}
swap(arr[i], arr[firstIndex]);
}
cout << "INSERTION SORT2\n";
}
cout << "INSERTION SORT3\n";
}
For starters it will not sort an array that has two elements due to this for loop
for (i = 0; i < n - 2; i++) //-1 ||-2//
Secondly, the variable firstIndex is not initialized by a value of the index i
firstIndex = arr[i];
So the condition in this if statement
if (arr[j] < arr[firstIndex])
does not make a sense.
Thirdly this inner for loop
for (j = i + 1;j < n - 1;j++)
ignores the last element of the array.
Fourth, this unconditional call of the function swap within the inner for loop
swap(arr[i], arr[firstIndex])
also does not make a sense.
The function can look the following way
void SelectionSort( int a[], size_t n )
{
for ( size_t i = 0; i < n; i++ )
{
size_t min = i;
for ( size_t j = i + 1; j < n; j++ )
{
if ( a[j] < a[min] )
{
min = j;
}
}
if ( min != i ) swap( a[i], a[min] );
}
}
And in main the variable size should have the type size_t - the type of the value of the expression with the operator sizeof
const size_t size = sizeof(array) / sizeof(array[0]);
And instead of the magic number 4 in for loops in main you should use the named constant size or you could use the range-based for loop as
for ( const auto &item : array )
{
cout << item << ' ';
}
cout << endl;
If you indeed mean the insertion sort method then a corresponding function can look for example the following way
void InsertionSort( int a[], size_t n )
{
for (size_t i = 1; i < n; i++)
{
if (a[i] < a[i - 1])
{
int tmp = a[i];
size_t j = i;
for ( ; j != 0 && tmp < a[j - 1]; --j )
{
a[j] = a[j - 1];
}
a[j] = tmp;
}
}
}
Thank you all for your help
I got it to work like this
#pragma once
#include <iostream>
using namespace std;
void swap(int &a,int &b)
{
int temp;
temp = b;
b = a;
a = temp;
}
void InsertionSort(int arr[],int n)
{
int i;
for (i = 0; i < n ; i++)
{
int firstIndex,j;
firstIndex = i;
for (j = i + 1;j < n ;j++)
{
if (arr[j] < arr[firstIndex])
{
firstIndex = j;
}
}
swap(arr[i], arr[firstIndex]);
}
}
The following is C++:
std::set<int> sorted_array({ 5,8,1,6 });
If you have duplicates and need to keep them, use:
std::multiset<int> sorted_array({ 5,8,1,6 });
Done. One line.

How do this program but in reverse, pattern

so i want output like this
1
123
12345
123
1
i already make the program but it only output these, and im confused how to output the bottom triangle
1
123
12345
here's my program
#include <iostream>
using namespace std;
int main() {
int n = 3 ;
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k++) {
cout << k;
}
cout <<endl;
}
return 0;
}
#Mojtaba's answer is a perffect extension to your approach.
However, I wanted to provide another method that is generally used in creating such strings that are formatted in a particular manner. It is common to create the entire pattern line by line and then print to the console all at once.
I have appropriately commented the code for your reference and it should be easy to understand:
#include <iostream>
#include <vector>
void pattern(int n) {
std::vector<std::string> lines; // store the first n lines to print later
int length = 2*n - 1; // length of each line
for(int i = 0; i < n; i++) {
std::string str = std::string(length, ' ');
for(int j = 1; j <= 2*i + 1; j++) {
str[n - i + j - 2] = j + '0';
// indexing can be figured by observing the pattern
}
lines.emplace_back(str);
}
for(int i = 0; i < n; i++) {
std::cout << lines[i] << std::endl;
}
for(int i = n-2; i >= 0; i--) {
std::cout << lines[i] << std::endl;
}
return;
}
int main() {
int n;
std::cin >> n;
pattern(n);
}
I added another for loop exactly like yours with different order from n-1. I modified your code to this:
int main() {
int n = 3 ;
int i, j, k;
for (i = 1; i <= n; i++) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k++) {
cout << k;
}
cout <<endl;
}
for (i = n - 1; i >= 1; i--) {
for (j = n; j > i; j--) {
cout << " ";
}
for (k = 1; k <= (2 * i - 1); k++) {
cout << k;
}
cout <<endl;
}
return 0;
}
Now it returns:
1
123
12345
123
1

all possible combinations to divide pack of candies

I have problem to solve and I'm stuck, I don't know how to start.
Suppose I have R childrens and S candies. I want to divide candies between childrens. Each child can get 0, 1, 2, 3 or 4 candies. How to find all the possibilities of such a division?
#include <iostream>
using namespace std;
void solve(int r, int s) {
if (s == 0)
{
cout << "no more candies" << endl;
return;
}
if (r == 0)
{
cout << "last child" << endl;
return;
}
for (int j = 0; j < 4 && j <= s; ++j)
{
cout << "r: " << r << " j: " << j << endl;
solve(r-1, s - j);
}
}
int main () {
int r, s;
cin >> r >> s;
solve(r, s);
return 0;
}
For now I have sth like this, I see in output that I have solutions here, but I don't know how to grab and store all possibilities into for example vector.
Just store counts and save variants at the last recursion level
vector<int> counts;
vector<vector<int>> sol;
void solve(int r, int s) {
if (s == 0)
{
sol.push_back(counts);
return;
}
if (r == 0)
{
return;
}
for (int j = 0; j <= 4 && j <= s; ++j)
{
counts[r - 1] += j;
solve(r - 1, s - j);
counts[r - 1] -= j;
}
}
int main() {
int r, s;
r = 3;
s = 5;
for (int j = 0; j < r; ++j)
counts.push_back(0);
solve(r, s);
for (int i = 0; i < sol.size(); i++) {
for (int j = 0; j < sol[i].size(); j++) {
cout << sol[i][j] << ' ';
}
cout << endl;
}
return 0;
}

Finding all saddle points in a matrix c++

I'm working on a code that finds all saddle points in a matrix. Both smallest in their row and biggest in their column, and biggest in their row and smallest in their column fall under the definition (of my university) of a saddle point. Being a beginner I managed to get half of it done (finding saddle points which are smallest in their row and biggest in their column) by copying parts of what we've done in class and typing it myself. I have been stuck on it for quite some time and can't figure how to add the saddle points which are biggest in their row and smallest in their column to the program.
This is what I have so far:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int x, y;
int pos_max(int j) //saddle points check
{
int max = 0;
for (int i = 1; i <= x - 1; i++) {
if (a[i][j] > a[max][j]) {
max = i;
}
}
return max;
}
int main() {
cout << "Enter the number of rows: ";
cin >> x;
cout << "Enter the number of columns: ";
cin >> y;
cout << "----------------------------" << endl;
for (int i = 0; i <= x - 1; i++) //input of the matrix
for (int j = 0; j <= y - 1; j++) {
cout << "a[" << i + 1 << ", " << j + 1 << "] = ";
cin >> a[i][j];
}
cout << "----------------------------\n";
for (int i = 0; i <= x - 1; i++) //visualization of the matrix
{
for (int j = 0; j <= y - 1; j++)
cout << a[i][j] << " ";
cout << endl;
}
cout << "----------------------------\n";
int r;
int flag = 0;
int i = y;
for (int j = 0; j <= y - 1; j++) {
r = pos_max(j);
for (i = 0; i <= y - 1; i++) {
if (a[r][i] < a[r][j]) {
break;
}
}
if (i == y) {
cout << "Saddle points are: ";
cout << "a[" << r + 1 << ", " << j + 1 << "] = " << a[r][j] << "\n";
flag = 1;
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
First, there is a logical error with your code. In the pos_max function, it will return the index of the element which is maximum in the column. There can be a case when there are multiple maximum with the same value in the column, however, it returns the one which is not the minimum in the row, hence your program won't be able to print that saddle point.
To solve this, you can either return an array of all indices which are maximum in a column and then check for each of those points if it's minimum in their respective column, but I think it's not a very elegant solution. In any case, you will again have to write the entire code for the other condition for saddle points, minimum in column and maximum in row.
Hence, I would suggest a change in strategy. You create 4 arrays, max_row, max_col, min_row, min_col, where each array stores the minimum / maximum in that row / column respectively. Then you can traverse the array and check if that point satisfies saddle point condition.
Here is the code:
#include <iostream>
#include <cstdlib>
using namespace std;
int a[10][10];
int max_row[10], max_col[10], min_row[10], min_col[10];
int x, y;
bool is_saddle(int i, int j) {
int x = a[i][j];
return (max_row[i] == x && min_col[j] == x) || (min_row[i] == x && max_col[j] == x);
}
int main() {
/* code to input x, y and the matrix
...
*/
/* code to visualize the matrix
...
*/
/* populating max and min arrays */
for (int i = 0; i <= x-1; ++i) {
max_row[i] = a[i][0], min_row[i] = a[i][0];
for (int j = 0; j <= y-1; ++j) {
max_row[i] = max(max_row[i], a[i][j]);
min_row[i] = min(min_row[i], a[i][j]);
}
}
for (int j = 0; j <= y-1; ++j) {
max_col[j] = a[0][j], min_col[j] = a[0][j];
for (int i = 0; i <= x-1; ++i) {
max_col[j] = max(max_col[j], a[i][j]);
min_col[j] = min(min_col[j], a[i][j]);
}
}
/* Check for saddle point */
for (int i = 0; i <= x-1; ++i) {
for (int j = 0; j <= y-1; ++j) {
if (is_saddle(i, j)) {
cout << "Saddle points are: ";
cout << "a[" << i + 1 << ", " << j + 1 << "] = " << a[i][j] << "\n";
flag = 1;
}
}
}
if (flag == 0) {
cout << "No saddle points\n";
}
cout << "----------------------------\n";
return 0;
}
#include <iostream>
using namespace std;
int getMaxInRow(int[][5], int, int, int);
int getMinInColumn(int[][5], int, int, int);
void getSaddlePointCordinates(int [][5],int ,int );
void getInputOf2dArray(int a[][5], int, int);
int main()
{
int a[5][5] ;
int rows, columns;
cin >> rows >> columns;
getInputOf2dArray(a, 5, 5);
getSaddlePointCordinates(a,rows,columns);
}
void getInputOf2dArray(int a[][5], int rows, int columns)
{
for (int i = 0; i < rows; i = i + 1)
{
for (int j = 0; j < columns; j = j + 1)
{
cin >> a[i][j];
}
}
}
void getSaddlePointCordinates(int a[][5],int rows,int columns)
{
int flag = 0;
for (int rowNo = 0; rowNo < 5; rowNo++)
{
for (int columnNo = 0; columnNo < 5; columnNo++)
{
if (getMaxInRow(a, rows, columns, rowNo) == getMinInColumn(a, rows, columns, columnNo))
{
flag = 1;
cout << rowNo << columnNo;
}
}
}
if (flag == 0)
cout << "no saddle point";
cout << "\n";
}
int getMaxInRow(int a[][5], int row, int column, int rowNo)
{
int max = a[rowNo][0];
for (int i = 1; i < column; i = i + 1)
{
if (a[rowNo][i] > max)
max = a[rowNo][i];
}
return max;
}
int getMinInColumn(int a[][5], int row, int column, int columnNo)
{
int min = a[0][columnNo];
for (int i = 1; i < row; i = i + 1)
{
if (a[i][columnNo] < min)
min = a[i][columnNo];
}
return min;
}
just take the reference arr(ref[size]) // memorization method to check the minimum and maximum value in it.
Here is the Code Implementation with time complexity O(n *n) & space complexity O(n):
#include <bits/stdc++.h>
using namespace std;
#define size 5
void util(int arr[size][size], int *count)
{
int ref[size]; // array to hold all the max values of row's.
for(int r = 0; r < size; r++)
{
int max_row_val = arr[r][0];
for(int c = 1; c < size; c++)
{
if(max_row_val < arr[r][c])
max_row_val = arr[r][c];
}
ref[r] = max_row_val;
}
for(int c = 0; c < size; c++)
{
int min_col_val = arr[0][c];
for(int r = 1; r < size; r++) // min_val of the column
{
if(min_col_val > arr[r][c])
min_col_val = arr[r][c];
}
for(int r = 0; r < size; r++) // now search if the min_val of col and the ref[r] is same and the position is same, if both matches then print.
{
if(min_col_val == ref[r] && min_col_val == arr[r][c])
{
*count += 1;
if((*count) == 1)
cout << "The cordinate's are: \n";
cout << "(" << r << "," << c << ")" << endl;
}
}
}
}
// Driver function
int main()
{
int arr[size][size];
for(int i = 0; i < size; i++)
{
for(int j = 0; j < size; j++)
cin >> arr[i][j];
}
int count = 0;
util(arr, &count);
if(!count)
cout << "No saddle points" << endl;
}
// Test case -> Saddle Point
/*
Input1:
1 2 3 4 5
6 7 8 9 10
1 2 3 4 5
6 7 8 9 10
0 2 3 4 5
Output1:
The cordinate's are:
(0,4)
(2,4)
(4,4)
Input2:
1 2 3 4 5
6 7 8 9 1
10 11 12 13 14 15
16 17 18 19 20
21 22 23 24 25
Output2:
No saddle points
*/

finding the most repeated elements in an array with length n

const int N=10;
int main()
{
int arr[N]={4,4,6,4,6,6,7,9,9,9};
for (int i = 0; i < N; i++)
for (int j=i+1; j<N; j++)
{
if (arr[i]==arr[j])
cout << arr[i];
}
return 0;
}
This gives all the repeated elements (meaning it will give 444,666,999). My problem is that I want the output to be just 4,6,9 and not that 4 was repeated three times. Obviously I gave my global constant a value of 10 but how can i do this for an "n" (unknown) number. Thanks.
At the beginning sort array
sort(arr, arr + n);
Then iterate and find the count of the most repeated element, you can do that like this :
int maxCnt = 0;
int curCnt = 1;
for (int i = 1; i < n; i++) {
if (arr[i] == arr[i - 1]) curCnt++;
else
{
maxCnt = max(maxCnt, curCnt);
curCnt = 1;
}
}
maxCnt = max(maxCnt, curCnt);
then iterate again accumulating curCnt and when curCnt == maxCnt output number
curCnt = 1;
for (int i = 1; i < n; i++) {
if (curCnt == maxCnt) cout << arr[i - 1] << ' ';
if (arr[i] == arr[i - 1]) {
curCnt++;
}
else curCnt = 1;
}
if (curCnt == maxCnt) cout << arr[n - 1] << endl;
This solution will output the most repeated numbers only once.
Use "range based for loop" for unknown array size (N).
Use std::map to calculate the count for each element.
Here is the code:
#include <map>
#include <iostream>
using namespace std;
int main()
{
const int arr[]{ 4,4,6,4,6,6,7,9,9,9 };
// Get count for each element.
map<int, int> elementCount;
for (const auto& e : arr)
{
elementCount[e] += 1;
}
// Get the highest count.
int highestCount = 0;
for (const auto& e : elementCount)
{
cout << e.first << " " << e.second << endl;
if (e.second > highestCount)
{
highestCount = e.second;
}
}
// Get the elements with the hightest count.
cout << endl << "Elements with the hightest count:" << endl;
for (const auto& e : elementCount)
{
if (e.second == highestCount)
{
cout << e.first << " ";
}
}
cout << endl;
return 0;
}