Incorrect output in Pascal's triangle program in C++ - c++

I was creating a Pascal's triangle program in C++, but the output displayed is not as expected.
Output Expected
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Output got
1
1 1
1 2 1
1 3 3 1
1 2 2 2 1
1 6 6 6 6 1
Till i = 4, output displayed is correct, but after that I couldn't figure out how it goes wrong. Hers is the source code to get reviewed
int main()
{ int num, a[37680], t = 0, b = 2, l;
cout<<"Enter the number of rows: ";
cin>>num;
for (int i = 1; i <= num; i++)
{
for (int j = 1; j <= (num - i); j++)
{
cout<<" ";
}
for (int k = 1; k <= i; k++)
{
l = k;
if (k == 1 || k == i)
{
a[t] = 1;
cout<<a[t]<<" ";
t+=1;
}
else
{
a[t] = a[t - b] + a[t - b - 1];
cout<<a[t]<<" ";
t+=1;
if ( l = (i - 1) )
{
b+=1;
}
}
}
cout<<endl;
}
return 0;}

Equality checking in c++ is done using == and not =, so:
if(l=(i-1))
Should be:
if(l==(i-1))

Related

my prim function isnt working quite right any help appreciated

im supposed to haveit start from any given location which it does but it just prints the same set over and over. any help would be appreciated
void graph::primms(int x)
{
int mincost = 0;
int min = infinite;
int oldindex;
int index;
bool mark[num+1];
int a,v;
for(int i = 1; i<num+1; i++)
{
mark[i] = false;
}
mark[x] = true;
for(int x = 1; x<num; x++){
for(a =1; a<num+1; a++)
{
for(v=1; v<num+1; v++)
{
if(!mark[v] && !mark[a] && garr[a][v] < min && garr[a][v] > 0)
{
min = garr[a][v];
index = v;
oldindex = a;
}
}
}
mark[v] = true;
cout << oldindex <<" -> "<< index<<endl;
mincost += min;
}
cout<<" total cost is"<<mincost;
}
example of my output:
2 -> 3
2 -> 3
2 -> 3
total cost is 3
this is the graph i am working with:
0 1 2 3 4
1 0 0 0 1
2 0 0 1 3
3 0 1 0 3
4 1 3 3 0

Generate all undirected graphs with n nodes

I'm trying to generate all the undirected graphs with n nodes, using recursive backtracking. I have to write their matrix (I don't know how is it called in english - in my language it would be adjacent matrix - is that right?) into a file.
For example:
input
3
output
8
0 0 0
0 0 0
0 0 0
0 0 0
0 0 1
0 1 0
0 0 1
0 0 0
1 0 0
0 0 1
0 0 1
1 1 0
0 1 0
1 0 0
0 0 0
0 1 0
1 0 1
0 1 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 1
1 1 0
Here is my program:
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("gengraf.in");
ofstream g("gengraf.out");
int st[100], n, adiacenta[100][100], l=1;
void tipar(int k)
{
for (int i = 1; i < k; i++)
{
for (int j = i+1; j < k; j++)
{
adiacenta[i][j] = adiacenta[j][i] = st[l];
}
l++;
}
for (int i = 1; i < k; i++)
{
for (int j = 1; j < k; j++)
{
g << adiacenta[i][j] << " ";
}
g << endl;
}
}
int valid(int k)
{
return 1;
}
void back(int k)
{
if (k == ((n - 1) * n / 2) + 1)
{
l = 1;
tipar(k);
g << endl;
}
else
{
for (int i = 0; i <= 1; i++)
{
st[k] = i;
if (valid(k))
{
back(k + 1);
}
}
}
}
int main()
{
f >> n;
g << pow(2, (n * (n - 1))/2);
g << endl;
back(1);
}
but my output is:
8
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 0
0 0 1
0 1 0
0 0 0
0 0 1
0 1 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 0
1 0 0
0 1 1
1 0 1
1 1 0
0 1 1
1 0 1
1 1 0
and I don't know how to fix that.
I see why does happen - I generate 2^(n*(n-1))/2) graphs (because that's how many undirected graphs with n nodes are), and instead of generating 8 distinct ones, I get only 4 distinct ones, shown 2 times.
That is (I suppose) because my program outputs a graph with, let's say, a link between the node 1 and 3 and another graph with a link between the node 3 and 1. And that is basically the same undirected graph.
So if I am right, I should make my program not show each graph twice and it should work. So basically I have to get rid of each graph with the "reversed" node (so if I got one with a link between 1 and 3, I shouldn't get another one with a link between 3 and 1 because they are the same).
Am I right?
If so, how can I do that?
Thanks.
Problems with your code:
Value of l in tipar() id not increased after assignment.
Size of adjacency matrix is n * n not k * k.
This code work as expected.
#include <iostream>
#include <fstream>
using namespace std;
ifstream f("gengraf.in");
ofstream g("gengraf.out");
int st[100], n, adiacenta[100][100], l=1;
int pow(int a, int b) {
int r = 1;
while (b) {
if (b&1) r *= a;
b >>= 1;
a *= a;
}
return r;
}
void tipar()
{
for (int i = 1; i <= n; i++)
{
for (int j = i+1; j <= n; j++)
{
adiacenta[i][j] = adiacenta[j][i] = st[l];
l++;
}
}
for (int i = 1; i <= n; i++)
{
for (int j = 1; j <= n; j++)
{
g << adiacenta[i][j] << " ";
}
g << endl;
}
}
int valid(int k)
{
return 1;
}
void back(int k)
{
if (k == (n * (n-1) / 2) + 1)
{
l = 1;
tipar();
g << endl;
}
else
{
for (int i = 0; i <= 1; i++)
{
st[k] = i;
if (valid(k))
{
back(k+1);
}
}
}
}
int main()
{
cin >> n;
g << pow(2, (n * (n - 1))/2);
g << endl;
back(1);
}

How to write this recursion with loops

I saw the following as an exercise in a website. It basically says write the following function without using recursion and without using structures like vector, stack, etc:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
At first I thought it was going to be easy, but I'm suprisingly struggling to accomplish it.
To understand it better, I defined it like a math function as the following:
f(x) = {1 if x = 0, f(x-1) + f(x-1) otherwise} (where + operator means concatenation and - is the normal minus)
However, Unrolling this made it harder, and I'm stuck. Is there any direct way to write it as a loop? And also, more generally, is there an algorithm to solve this type of problems?
If you fiddle with it enough, you can get at least one way that will output the ordered sequence without revisiting it :)
let n = 5
// Recursive
let rec_str = ''
function rec(n) {
if (n != 0) {
rec_str += n
rec(n-1);
rec(n-1);
}
}
rec(n)
console.log(rec_str)
// Iterative
function f(n){
let str = ''
for (let i=1; i<1<<n; i++){
let t = i
let p = n
let k = (1 << n) - 1
while (k > 2){
if (t < 2){
break
} else if (t <= k){
t = t - 1
p = p - 1
k = k >> 1
} else {
t = t - k
}
}
str += p
}
console.log(str)
}
f(n)
(The code is building a string, which I think should be disallowed according to the rules, but only for demonstration; we could just output the number instead.)
void loop(int n)
{
int j = 0;
int m = n - 1;
for (int i = 0; i < int(pow(2, n)) - 1; i++)
{
j = i;
if (j == 0)
{
std::cout << n << " ";
continue;
}
m = n - 1;
while (true)
{
if (m == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
if (j >= int(pow(2, m)))
{
j = j - int(pow(2, m)) + 1;
}
if (j == 1)
{
std::cout << m << " ";
m = n - 1;
break;
}
else
{
j--;
}
m--;
}
}
std::cout << std::endl;
}
For n = 3 for instance
out = [3 2 1 1 2 1 1]
indexes = [0 1 2 3 4 5 6]
Consider the list of indexes; for i > 0 and i <= 2^(m) the index i has the same value as the index i + 2^(m)-1 where m = n - 1. This is true for every n. If you are in the second half of the list, find its correspondent index in the first half by this formula. If the resulting number is 1, the value is m. If not, you are in a lower level of the tree. m = m - 1 and repeat until the index is 1 or m =1, in which case you've reached the end of the tree, print 1.
For instance, with n = 4, this is what happens with all the indexes, at every while step. p(x) means the value x gets printed at that index. A / means that index has already been printed.:
n = 4,m = 3
[0 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
m = 3
[p(n=4) 1 2 3 4 5 6 7 8 9 10 11 12 13 14]
if(i >=2^3) -> i = i -2^3 + 1)
[/ 1 2 3 4 5 6 7 1 2 3 4 5 6 7]
if(i == 1) -> print m, else i = i -1
[/ p(3) 1 2 3 4 5 6 p(3)1 2 3 4 5 6]
m = 2
if (i >=2^2) -> i = i - 2^2 +1
[/ / 1 2 3 1 2 3 / 1 2 3 1 2 3]
if(i == 1) -> print m, else i = i -1
[ / / p(2) 1 2 p(2) 1 2 / p(2) 1 2 p(2) 1 2]
m = 1
if (m == 1) -> print(m)
[ / / / p(1) p(1) / p(1) p(1) / / p(1) p(1) / p(1) p(1)]
Therefore the result is:
[4 3 2 1 1 2 1 1 3 2 1 1 2 1 1]
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
Idea is to save result from the previous computation of each number. Full code:
void rec(int n) {
if (n != 0) {
cout << n << " ";
rec(n-1);
rec(n-1);
}
}
void via_loop(int n) {
string prev = "1 ", ans = "1 ";
for (int i = 2; i <= n; i++) {
ans = to_string(i) + " " + prev + prev;
prev = ans;
}
cout << ans;
}
int main() {
int n = 5;
cout << "Rec : ";
rec(n);
cout << endl;
cout << "Loop: ";
via_loop(n);
cout << endl;
}
Output:
Rec : 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1
Loop: 5 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1 4 3 2 1 1 2 1 1 3 2 1 1 2 1 1

changing for loop to block parition

I want to change the for-loop to block scheme
I have this for loop that does this:
let say n = 8
and node = 4
n: [1][2][3][4][5][6][7][8]
id: 0 1 2 3 0 1 2 3
id = 0;
while (id < node){
for (i = id + 1; i <= n; i = i + node)
{
//do stuff here
id = i;
}enter code here
id+1;
}//end while
and i want it to do this:
n = 8
node= 4
n: [1][2][3][4][5][6][7][8]
id: 0 0 1 1 2 2 3 3
n = 16
node = 4
n: [1][2][3][4][5][6][7][8] ... [13][14][15][16]
id: 0 0 0 0 1 1 1 1 ... 3 3 3 3
n = 8
node= 2
n: [1][2][3][4][5][6][7][8]
id: 0 0 0 0 1 1 1 1
where each id is assign to the top n show in examples
I have this but it only works for the specific scenario n= 8 & node = 4
...
b = id + 1
for (i = n-(n-(id+b)); i <= (n-(n-(id+b))+1); i+= 1)
...
I perhaps misunderstood your question but this gives the output for id as you described:
for (int i = 0; i < n; i++)
{
id = i / (n / node);
// do stuff
}
I use n starting from 0, but if you start from 1, just adjust the calculation by ofsetting everything to n-1.
Try this code:
int node = 4;
int n = 16;
for (id = 0; id < node; id++) {
for(int j = 0; j < n / node; j++) {
//do some stuff
}
}
Or you can use this code:
int node = 4;
int n = 16;
for (int i = 0; i < node; i++) {
id = i;
for(int j = 0; j < n / node; j++) {
//do some stuff
}
}
They do the same.

Pascal's Triangle using mainly functions in C++

I was trying to write a code that would display pascals triangle. Instead of displaying the result as :
my result is displayed as
1
1 1
1 2 1
1 3 3 1
Please help me figure out how to modify it to be able to get the actual triangle. I cant use arrays and pointers since those aren't covered in my class yet. Here's my code:
#include "stdafx.h"
#include <iostream>
using namespace std;
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
cin >> n;
PascalsTriangle(n);
return 0;
}
void PascalsTriangle (int n){
int i,j,x;
for(i=0;i<n;i++)
{
x=1;
for(j=0;j<=i;j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}
Here is the updated version. Works for any n. I've added a function to return the number of digits in a number since that computation is needed each iteration of the inner loop.
#include <iostream>
#include <string>
using namespace std;
void PascalsTriangle(int);
int main()
{
int n;
cout << "Enter the number of rows you would like to print for Pascal's Triangle: ";
cin >> n;
cout << endl;
PascalsTriangle(n);
return 0;
}
int numdigits(int x)
{
int count = 0;
while(x != 0) {
x = x / 10;
++count;
}
return count;
}
void PascalsTriangle (int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
len = string((n-i-1)*(n/2), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x) - 1;
if(n % 2 == 0)
cout << y << string(n - 1 - maxlen, ' ');
else {
cout << y << string(n - 2 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUTS:
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
UPDATE for a more tighter triangle:
void PascalsTriangle(int n)
{
int i, j, x, y, maxlen;
string len;
for(i = 0; i < n; i++) {
x = 1;
if(n % 2 != 0)
len = string((n-i-1)*(n/2), ' ');
else
len = string((n-i-1)*((n/2)-1), ' ');
cout << len;
for(j = 0; j <= i; j++) {
y = x;
x = x * (i - j) / (j + 1);
maxlen = numdigits(x);
if(n % 2 == 0)
cout << y << string(n - 2 - maxlen, ' ');
else {
cout << y << string(n - 1 - maxlen, ' ');
}
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle: 3
1
1 1
1 2 1
Enter the number of rows you would like to print for Pascal's Triangle: 6
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
Enter the number of rows you would like to print for Pascal's Triangle: 9
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
Enter the number of rows you would like to print for Pascal's Triangle: 12
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
1 5 10 10 5 1
1 6 15 20 15 6 1
1 7 21 35 35 21 7 1
1 8 28 56 70 56 28 8 1
1 9 36 84 126 126 84 36 9 1
1 10 45 120 210 252 210 120 45 10 1
1 11 55 165 330 462 462 330 165 55 11 1
Try this :
#include <iostream>
using namespace std;
int main()
{
int n,k,i,x;
cout << "Enter a row number for Pascal's Triangle: ";
cin >> n;
for(i=0;i<=n;i++)
{
x=1;
for(k=0;k<=i;k++)
{
cout << x << " ";
x = x * (i - k) / (k + 1);
}
cout << endl;
}
return 0;
}
EDITED:
#include <iostream>
using namespace std;
int main()
{
int n,coef=1,space,i,j;
cout<<"Enter number of rows: ";
cin>>n;
for(i=0;i<n;i++)
{
for(space=1;space<=n-i;space++)
cout<<" ";
for(j=0;j<=i;j++)
{
if (j==0||i==0)
coef=1;
else
coef=coef*(i-j+1)/j;
cout<<" "<<coef;
}
cout<<endl;
}
}
Do you expect this result?
1111
123
13
1
You need to add endl or constant string equivalent to "\r\n" to the end of the output string, or use commas in output, then, for example:
"1111,123,13,1"
"1,11,121,1331"
If you want it to look like a 'triangle', that is, a symmetric looking isosceles triangle, try this code for your PascalTriangle function. The only problem with this is that when you get larger digits, it will break some of the symmetry but up to 5 rows it'll work fine.
void PascalsTriangle(int n)
{
int i, j, x;
string len;
for(i = 0; i < n; i++)
{
x = 1;
len = string(n - i - 1, ' ');
cout << len;
for(j = 0; j <= i; j++)
{
cout << x << " ";
x = x * (i - j) / (j + 1);
}
cout << endl;
}
}
OUTPUT
Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
As opposed to:
Enter the number of rows you would like to print for Pascal's Triangle: 5
1
1 1
1 2 1
1 3 3 1
1 4 6 4 1
#include <iostream>
using namespace std;
const int MAXC = 13; //-- Max column constant
const int MAXF = 7; //-- Max row constant
int m, n, k, x, y; //-- Counters and accumulators for loops
int arrayTriangulo[MAXF][MAXC]; // Array that stores the values of the Pascal Triangle
int main() {
m = (MAXC/2); // Middle Column
k = (MAXC/2); // Middle row
//-- 1.- Fill in the Array from Left to Right and from Top to Bottom
//-- 2.- Fill in the Array starting from row 0 through 13 (MAXF)
for ( x = 0; x < MAXF; x++ ) {
n = 1;
//-- 3.- Fill in the Array starting from Column 0 through 7 (MAXC)
for ( y = 0; y < MAXC; y++ ) {
//-- Assign 0 to the Array element that is not part of the triangle.
arrayTriangulo[x][y] = 0;
//-- 4.- If it is on the edges of the triangle assigns the value of "n". Which we initialize in 1.
if (( y == m ) || ( y == k )) {
arrayTriangulo[x][y] = n;
}
//-- 5.- For the rest of the internal values of the triangle other than the edges.
//-- The sum of the value is assigned (upper left row -1) + (upper right row + 1)
if ( ( x > 1 ) && ( x < MAXF ) && ( y < MAXC-1 ) ) {
arrayTriangulo[x][y] = arrayTriangulo[x-1][y-1] + arrayTriangulo[x-1][y+1];
}
//-- 6.- Finally Draw the Triangle by omitting the values at zero.
if ( arrayTriangulo[x][y] > 0 )
cout << arrayTriangulo[x][y] << " ";
else
cout << " ";
}
cout << endl;
m--;
k++;
}
return 0;
}