pascal triangle in c without array [duplicate] - c

This question already has answers here:
Pascal's Triangle in C
(4 answers)
Closed 1 year ago.
I tried to code a program that will give the pascal triangle without using arrays and keeping in mind the formula that each element of the pascal triangle can be calculated as n choose k" and written like this:
n choose k = n! / k!(n-k)!
(for both n and k starting from 0)
so I also had to define the factorial function and it worked for the first 14 lines.
but in line 15 and more my numbers started to decrease and became also negative but I don't understand why this happened.
Here is the code:
#include <stdio.h>
int factorial(int a);
int main()
{
int row, j, i, space, tot;
scanf("%d", &row);
space=row;
for(i=0; i<row; i++)
{
for(space=0; space<row-i; space++)
{ printf(" "); }
for (j = 0; j <= i; j++)
{
if (j == 0 || i == 0)
{ tot=1; }
else
{
int n=factorial(i);
int k=factorial(j);
int z=factorial(i-j);
tot= n/(k*z);
}
printf("%6d", tot);
}
printf("\n");
}
}
int factorial(int a)
{
int fact=1;
for (int m=1; m<=a; m++)
{ fact*=m; }
return fact;
}
this is my output in line 15:
1 0 1 5 14 29 44 50 44 29 14 5 1 0 1
but the actual output should be this:
1 14 91 364 1001 2002 3003 3432 3003 2002 1001 364 91 14 1
I couldn't find the problem so I would be happy and thankful if anyone could help me.

If you don't care much about computation time then you could compute coefficient directly from their recursive definition.
int pascal(int x,int y) {
if (x==0 || y==0) return 1;
return pascal(x-1,y)+pascal(x,y-1);}

Related

Calculate maximum path cost for a matrix in C

I am learning c and encountered maximum cost path question in which
Rules:
matrix is n x n size
Starting from the cell (bottommost leftmost cell), you want to go to the topmost
rightmost cell in a sequence of steps. In each step, you can go either right or up from
your current location.
I tried to solve using dynamic programming and this is the function I have written
computecost(int *utr,int n)//utr is the input matrix
{
int *str;
int i,j;
str=(int *)malloc(n*n*sizeof(int));
for(j=0;j<n;j++)//intialization of bottom row
{
str[n*(n-1)+j]=utr[n*(n-1)+j];
}
for(i=n-2;i>=0;i--)
{
for(j=0;j<n;j++)
{
str[n*i+j]=utr[n*i+j]+max(str[n*(i+1)+j],str[n*(i+1)+(j+1)]);
}
}
printf("%d",str[n*0+0]);
return 0;
}
and this is the input
for(i=0;i<n;i++)
{
for(j=0;j<n;j++)
{
scanf("%d",&str[n*i+j]);
}
}
but
for the matrix 5 x5
1 4 8 2 9
32 67 18 42 1
4 86 12 7 1
8 4 12 17 44
1 43 11 45 2
the desired output is 272 but I am getting 211.
the output matrix for my case
1 43 11 45 2
51 47 57 62 46
55 143 74 69 47
175 210 92 111 52
211 214 119 113 64
Can anyone help me?
You don't need dynamic programming for this since there are no overlapping sub-problems. Just use a simple recursion.
const int n = 5;
int mat[n][n] = {
{1,4,8,2,9},
{32,67,18,42,1},
{4,86,12,7,1},
{8,4,12,17,44},
{1,43,11,45,2}
}; // input matrix
int f(int x, int y, int sum){
if(x == 0 && y == 4)
return sum;
int p = 0, q = 0;
if(x - 1 >= 0)
p = f(x-1, y, sum + mat[x-1][y]);
if(y + 1 <= 4)
q = f(x, y+1, sum+mat[x][y+1]);
return max(p,q);
}
int main(){
int maxSum = f(4,0, mat[4][0]);
printf("%d\n", maxSum);
}
You were not very far to succeed.
In practice, you did not initialize correctly the bottom row.
Moreover, there was a little mistake in the iteration calculation.
This is the corrected code.
As said in a comment, it could be further simplified, by avoiding the use of a new array, simply updating the input array.
#include <stdio.h>
#include <stdlib.h>
int max (int a, int b) {
return (a > b) ? a : b;
}
int computecost(int *utr,int n) { //utr is the input matrix
int *str;
str = malloc (n*n*sizeof(int));
str[n*n - 1] = utr[n*n - 1];
for (int j = n-2; j >= 0; j--) { //intialization of bottom row {
str[n*(n-1)+j] = utr[n*(n-1)+j] + str[n*(n-1)+j+1]; // corrected
}
for (int i=n-2; i>=0; i--) {
str[n*i+n-1] = utr[n*i+n-1] + str[n*(i+1)+n-1];
for(int j = n-2; j >= 0; j--) {
str[n*i+j] = utr[n*i+j] + max(str[n*(i+1)+j],str[n*i + j+1]); // corrected
}
}
int cost = str[0];
free (str);
return cost;
}
int main() {
int A[25] = {
1,43,11,45,2,
8,4,12,17,44,
4,86,12,7,1,
32,67,18,42,1,
1,4,8,2,9
};
int ans = computecost (A, 5);
printf ("%d\n", ans);
return 0;
}

Check whether a given Matrix(m*n) has any matrix inside of it that can be transposed

I need to check if I can find inside of given matrix size of 5*8
a matrix that has a transpose and if there is more than one I must find the biggest one.
example of a given matrix
1 2 0 3 2 1 0 7
2 3 4 1 2 3 4 5
3 4 6 2 5 6 7 6
4 5 7 3 6 8 9 8
6 7 1 4 7 9 0 9
in this matrix we can find a matrix 4x4
that has transpose and its the biggest matrix in the main matrix
1 2 3 4
2 5 6 7
3 6 8 9
4 7 9 0
#include <stdio.h>
#define M 4
#define column 5
#define row 8
int main()
{
int matrixA[5][8];
printf("please enter a matrix to check if there is a transpose matrix\n");
for (int i = 0; i < column; i++)
{
for (int j = 0; j < row; j++)
{
printf("please enter %d row and %d column: ", i + 1, j + 1);
scanf("%d", &matrixA[i][j]);
}
}
transpose(matrixA, column, row);
}
void transpose(int A[][row], int c, int r)
{
int matrixAT[M][M];
for (int size = r; size > 0; size--)
{
for (int j = 0; j < c - size + 1; j++)
{
for (int b = 0; b <= r - size; b++)
{
printf("Checking Matrix at row: %d , column: %d ,size: %dx%d", j, b, size, size);
for (int k = j, w = 0; k < size + j; k++, w++)
{
for (int l = b, z = 0; l < size + b; l++, z++)
{
matrixAT[w][z] = A[k][l];
}
printf("/n");
}
if (IsSymmetric(matrixAT, size))
printf("Matrix found");
}
}
}
}
int IsSymmetric(int mat[M][M], int size)
{
int flag = 0;
for (int i = 0; i < size; i++)
{
for (int j = 0; j < size; j++)
{
if (mat[i][j] == mat[j][i]) flag++;
}
}
return flag == size * size ? 1 : 0;
}
this is my code i dont know what im doing wrong
Your IsSymmetric is slow as it always check all elements why not stop on first inequality instead? Also copying it to temp array again and again ...
The main problem is You are not checking every position and size as you call transpose(matrixA, column, row); only once outside the loops ...
Also your main does not return anything and its declared as int ...
I would start with brute force like this:
#define column 5
#define row 8
int IsSymmetric(int mat[column][row], int i0,int j0,int size) // check n*n sub matrix at i0,j0 no need to copy again and again to temp array
{
for (int i = 0; i < size; i++)
for (int j = 0; j < size; j++)
if (mat[i0+i][j0+j] != mat[i0+j][j0+i]) return 0;
return 1;
}
int min(int a,int b){ return (a<b)?a:b; } // not sure if min is present in your environment if is comment this line out
int main()
{
int matrixA[5][8];
...
for (int i = 0; i < column; i++)
for (int j = 0; j < row; j++)
for (int n = 1; n <= min(column-i,row-j); n++)
if (IsSymmetric(matrixA,i,j,n))
{
// here do what you want with the i,j,n*n sub matrix
// like remember position and size for the biggest n
}
...
return 0; // return value as you declared int main
}
Hope I did not make any typo in here as I just wrote this into answer editor from your original code.
How ever as you can see its O(n^4) complexity (on average O(n^3)) which is really slow. However for your small matrix its not a problem.
In case you need something faster then we need to know more about the data ... for example what is the range of the values? Some hints:
on positive IsSymmetric test one cell bigger submatrix without testing the previous elements again (recursively increasing diagonal).
use histogram to detect values that might be only on diagonals (appear once globally or odd times locally)
Using the incremental symmetry test results in O(n^3) solution:
//---------------------------------------------------------------------------
#define column 5
#define row 8
//---------------------------------------------------------------------------
void submatrix_print(int mat[column][row], int i0,int j0,int n,int m)
{
int i,j;
printf("%i*%i at %i,%i\r\n",n,m,i0,j0);
for (i=0;i<n;i++,printf("\r\n"))
for (j=0;j<m;j++)
printf("%1i ",mat[i0+i][j0+j]);
}
//---------------------------------------------------------------------------
void submatrix_print_transposed(int mat[column][row], int i0,int j0,int n,int m)
{
int i,j;
printf("%i*%i at %i,%i\r\n",n,m,i0,j0);
for (i=0;i<m;i++,printf("\r\n"))
for (j=0;j<n;j++)
printf("%1i ",mat[i0+j][j0+i]);
}
//---------------------------------------------------------------------------
int min(int a,int b){ return (a<b)?a:b; }
int submatrix_symmetric(int mat[column][row], int i0,int j0) // returns biggest symetric submatrix size >=1 found at i0,j0
{
int i,n,N;
N=min(column-i0,row-j0); // max size that still fits into matrix
for (n=2;n<N;n++) // test all sizes above 1
for(i=0;i<n-1;i++) // only test newly added cells to last sub matrix
if (mat[i0+n-1][j0+i]!=mat[i0+i][j0+n-1])
return n-1; // first non match means last tested size i svalid
return n; // no mismatches mean full size is valid
}
//---------------------------------------------------------------------------
int main()
{
int mat[5][8]=
{
1,2,0,3,2,1,0,7,
2,3,4,1,2,3,4,5,
3,4,6,2,5,6,7,6,
4,5,7,3,6,8,9,8,
6,7,1,4,7,9,0,9,
};
submatrix_print(mat,0,0,5,8);
// submatrix_print_transposed(mat,0,0,5,8);
int i,j,n,i0=0,j0=0,n0=0;
for(i=0;i<column;i++)
for(j=0;j<row;j++)
{
n=submatrix_symmetric(mat,i,j);
if (n0<n){ n0=n; i0=i; j0=j; }
}
submatrix_print(mat,i0,j0,n0,n0);
return 0;
}
//-------------------------------------------------------------------------
The result of the code is:
5*8 at 0,0 // input matrix
1 2 0 3 2 1 0 7
2 3 4 1 2 3 4 5
3 4 6 2 5 6 7 6
4 5 7 3 6 8 9 8
6 7 1 4 7 9 0 9
4*4 at 1,3 // biggest symmetric sub matrix found
1 2 3 4
2 5 6 7
3 6 8 9
4 7 9 0
you can make a function that check if the matrix ican be transposed or no
and another function that take evry time a part from the main matrix and you move it everytime and check it with 1st function
example :
1st matrix :m[1][1] starting from zero
1 2
2 3
2 matrix :m[2][2] starting from one
2 0
3 4
then when you finish with 2 demension matrix you go to 3
till the end
i hope you understand me and sorry for my bad english

k largest elements exercise from geeksforgeeks

I am working on an exercise "k largest elements" from geeksforgeeks.org
https://practice.geeksforgeeks.org/problems/k-largest-elements/0
The task:
Given an array of N positive integers, print k largest elements from the array. The output elements should be printed in decreasing order.
Input:
The first line of input contains an integer T denoting the number of test cases. The first line of each test case is N and k, N is the size of array and K is the largest elements to be returned. The second line of each test case contains N input C[i].
Output:
Print the k largest element in descending order.
Constraints:
1 ≤ T ≤ 100
1 ≤ N ≤ 100 (actually 1000 as someone identified)
K ≤ N
1 ≤ C[i] ≤ 1000*
Example:
Input:
2
5 2
12 5 787 1 23
7 3
1 23 12 9 30 2 50
Output:
787 23
50 30 23
Explanation:
Testcase 1: 1st largest element in the array is 787 and second largest is 23.
Testcase 2: 3 Largest element in the array are 50, 30 and 23.
I have constructed a solution, which works with the initial test case, but later throws a segmentation fault. I cannot understand where could I get the segmentation fault:
Runtime Error:
Segmentation Fault (SIGSEGV)
Runtime Error
The problem with these exercises is that I do not know the input data to the test case, which generates the error. Bellow you will find my code, which is rather simple. Perhaps you can help me to identify what could cause the segmentation fault.
#include <stdio.h>
static int Arr[1024], Res[1024];
int main()
{
int t=0;
scanf("%d", &t);
while(t--)
{
int n=0,k=0, i=0,j=0,z=0;
scanf("%d %d", &n, &k);
// if(n>1000)
// printf("Gotya");
for(i=0; i<n; i++)
{
scanf("%d", &Arr[i]);
}
i=0;
int max_l = 0, max_h = 1000, j_max = 0;
for(i=0; i<k; i++)
{
for(j=0; j<n; j++)
{
if(Arr[j] >= max_l)
{
max_l = Arr[j];
j_max = j;
}
}
Res[i]= max_l;
max_l = 0;
Arr[j_max] = 0;
j_max = 0;
}
for(z=0; z<k; z++)
{
printf("%d ", Res[z]);
}
printf("\n");
}
return 0;
}
This site does not seem to be abiding by their constraints.
I made a login and modified the code to print if N>1000. The value of N is 20567
Wrong Answer. !!!Wrong Answer
Possibly your code doesn't work correctly for multiple test-cases (TCs).
The first test case where your code failed:
Input:
20567 18428
9737 16220 4527 21952 22174 12861 29801 8125 13670 9713 5742 14988 31137 21891 25646 18474 18286 30312 6105 19031 18587 15877 14546 29756 18364 24690 12129 16209 378 27774 16552 18302 8238 10483 1752 12929 5551 22299 14756 9871 18279 32386 23286 5182 16557 9726 7137 22434 24399 7661 3544 29878 11885 16318 29725 29438 25486 18099 18811 7275 12781 9700 20024 9087 26644 32648 12870 29873 2988 8560 12217 14099 26516 10964 10622 16434 16432 16210 8777 32574 8708 27444 8143 9067 32385 7410 20022 406 2846 22519 30665 32044 5803 1192 9457 30792 18658 419 30816 3867 64 23108 7056 8849 16915 18030 20332 30257 28883 22408 30029 25926 15541 30405 9255 29500 638 6313 7685 15180 3221 18889 14770 860 27229 30930 5305 30240 20929 8652 8592 18566 16145 16032 26129 20049 18188 8408 32297 16899 20286 6311 14036 17409 8332 3369 21833 21746 2061 27115 24177 20328 31259 1454 29342 9410 27562 26216 4474 24913 21977 1676 23102 15289 6087 32651 7204 13210 10920 15771 19230 880 23576 8375 11464 2706.................
Its Correct output is:
32768 32768 32766 32765 32761 32759 32757 32756 32756 32755 32754 32752 32747 32747 32747 32746 32743 32742 32741 32740 32739 32738 32738 32735 32735 32735 32733 32733 32732 32731 32730 32728 32728 32726 32726 32726 32725 32724 32719 32718 32718 32716 32714 32714 32708 32706 32706 32698 32694 32694 32691 32690 32690 32689 32688 32687 32684 32682 32676 32675 32672 32670 32663 32660 32658 32657 32657 32656 32651 32648 32646 32645 32644 32643 32638 32637 32637 32637 32637 32635 32632 32630 32630 32625 32625 32625 32623 32622 32622 32620 32619 32618 32616 32614 32614 32613 32613 32612 32608 32606 32606 32605 32598 32596 32593 32591 32589 32588 32586 32586 32586 32582 32582 32581 32580 32580 32579 32578 32574 32573 32571 32571 32567 32567 32566 32564 32564 32563 32562 32560 32560 32559 32559 32558 32555 32554 32552 32551 32551 32551 32550 32549 32549 32547 32547 32546 32544 32544 32543 32543 32540 32539 32538 32538 32537 32535 32533 32533 32533 32532 32531 32528 32527 32527 32526 32525 3252.................
And Your Code's output is:
Gotya
However, with the correct length of the array Arr and Res, you get an error of
Expected Time Limit < 1.996sec
Hint : Please optimize your code and submit again.
I leave this up to you.
Hint - Use qsort for a better sorting performance.
A set of points over a straight line is defined as correlative to some K if the absolute difference between any two points is a multiple of K. Given N (2 <= N <= 100000) points and some integer K (1 <= K <= 1000). Your task is to find the largest set which is correlative to K. You can assume that only one largest set exists. N and K will be in the first line of the input. N lines will follow, each one with a single integer, representing the location of one of the points. Print the size of the largest set of points which is correlative to K, in the first line of the input. Remaining lines will contain the points of the set, one per line, in increasing order.
Case 1:
For the input provided as follows:
5 2
1
2
3
4
5
Output of the program will be:
3
1
3
5
Case 2:
For the input provided as follows:
6 4
10
15
12
16
20
32
Output of the program will be:
4
12
16
20
32
#include <bits/stdc++.h>
using namespace std;
// function to find remainder set
int findSet(int arr[], int n, int k, int m) {
vector remainder_set[k];
// calculate remainder set array
// and push element as per their remainder
for (int i = 0; i < n; i++) {
int rem = arr[i] % k;
remainder_set[rem].push_back(arr[i]);
}
// check whether sizeof any remainder set
// is equal or greater than m
for (int i = 0; i < k; i++) {
if (remainder_set[i].size() >= m) {
cout <<m<< "\n";
for (int j = 0; j < m; j++){
cout << remainder_set[i][j] << "\n";
}
return 1;
}
}
return 0;
}
// driver program
int main() {
int n,k;
cin>>n>>k;
int arr[n];
for(int i=0;i<n;i++)
cin>>arr[i];
int z;
int m = sizeof(arr)/sizeof(int);
for(int i=m;i>0;i--)
{
z=findSet(arr, n, k, i);
if(z==1)
break;
}
}

how to print a table of even squares?

This program prompts the user a number and then outputs a table of even squares ranging from 2 to the number.
#include <stdio.h>
int main(void)
{
int i, n;
puts(This program prints a table of even squares.);
printf("Enter range of the squares square: ");
scanf("%d", &n);
for (i = 2; i * i <= n; i += 2)
printf("%d\n", i * i);
return 0;
}
for example:
Enter range of the squares: 123
2 4
4 16
6 36
8 64
10 100
The problem is did not print 121 (which is 11 * 11). I am new to C and not really good in using loops. Please help!
for (i = 2; i * i <= n; i += 2)
You're starting at 2 and incrementing by 2. i will never be 11.

Finding path maximum in 2D array

Halloween is round the corner and it's time for trick-or-treating. You reside at the top left corner of a n-by-n town map and heading to the halloween party located at the bottom right corner. While on your trip, you decide to visit a minimal number of houses to get treats. You have a map of town with information of the amount of treats (≥ 0) available at each location. As an example, the town map for n=3 is shown below.
6 8 2
4 5 1
3 9 10
To get the maximum treats, you will start from home (6), then head east to (8), then south to (5), then south to (9), then east to (10) and end up at the party.
So the number of treats is 6+8+5+9+10=38.
Notice that to visit a minimal number of houses, it necessitates that you either travel east or south from one house to the next until you arrive at the party. To obtain the maximum treats, track the current maximum as you visit each home.
6, 14, 2+14=16
10, 5+max(10,14)=19
3+10=13
So the program needs to be choosing the maximum value to add let's say for 10 and 14, i will choose to add 14. But I have trouble with this using for loops. Anyone can help?
1 #include <stdio.h>
2
3 #define SIZE 10
4
5 int pathmax(int map[][SIZE], int n);
6 void read(int map[][SIZE], int n);
7 int max(int x, int y);
8
9 int main(void)
10 {
11 int map[SIZE][SIZE], n;
12
13 printf("Enter n: ");
14 scanf("%d", &n);
15
16 read(map,n);
17
18 printf("Maximum: %d\n", pathmax(map,n));
19
20 return 0;
21 }
22
23 int max(int x, int y)
24 {
25 if (x > y)
26 return x;
27 else
28 return y;
29 }
30
31 int pathmax(int map[][SIZE], int n)
32 {
33 int k, i, j;
34
35 for (k = 1; k < 2*n-1; k++)
36 for (i = 0; i < n; i++)
37 for (j = 0; j < n; j++)
if(i+j==k)
{
if (i==0)
map[i][j] += map[i][j-1];
else if (j == 0)
map[i][j] += map[i-1][j];
else
map[i][j] += max(map[i-1][j], map[i][j-1];
}
}
Recursive solution, will teacher believe you wrote it?
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define MAXTREAT 10
#define GRID 3
int map [GRID][GRID];
int maxtreats;
void explore(int x, int y, int treats)
{
treats += map [y][x];
if (x == GRID-1 && y == GRID-1) { // reached bottom right?
if (treats > maxtreats) // check result
maxtreats = treats; // finish recursion
} else { // recurse
if (x+1 < GRID)
explore (x+1, y, treats); // go east
if (y+1 < GRID)
explore (x, y+1, treats); // go south
}
}
int main()
{
int x, y;
srand ((unsigned int)time(NULL)); // seed random num gen
for (x=0; x<GRID; x++) { // set up random map
for (y=0; y<GRID; y++) {
map[y][x] = 1 + rand() % MAXTREAT;
printf ("%4d", map[y][x]);
}
printf ("\n");
}
explore (0, 0, 0);
printf ("Max treats %d\n", maxtreats);
return 0;
}

Resources