Pascal's triangle with modification - c

I wrote a function to print Pascal's triangle with modifications.
The sides of the triangle will appear in ascending order instead of the value 1.
Each values at the base of the triangle will continue to contain the sum of the 2 members above it.
Also need to print the max value of a given level.
Example :
Pascal Triangle With Modification Example
void printTriangle2(int rows,int level) {
int i =0,j = 0,space,res = 0, isLevel = 0,max = 0;
for (i = 0 ; i<rows ; i++){
if (i == level)
isLevel = 1;
else isLevel = 0;
for (space = 1 ; space <= rows - i ; space++) {
printf(" ");
}
for (j = 0 ; j <= i ; j++) {
if (i == 0 || j == 0)
res++;
else {
res = res * (i - j + 1) / j;
}
if (isLevel == 1) {
if (res > max)
max = res;
}
printf("%4d",res);
}
printf("\n");
}
printf(" the max value is : %d",max);
}
my output for the input rows = 5 , level = 3:
Output Example
I have an issue with the calculation of res if the value is not in the side of the triangle
res = res * (i - j + 1) / j;
What am I doing wrong?

Related

Increased Pascal Triangle printed with wrong values - C

I want to print a triangle that is similar to Pascal Triangle but the sides are increased instead of containing the value 1.
Regular Pascal Triangle:
Wanted Triangle:
Regular Pascal method:
void PascalTriangle(int rows) {
int i =0,j = 0,space,coef = 0;
for (i = 0 ; i<rows ; i++){
for (space = 1 ; space <= rows - i ; space++)
printf(" ");
for (j = 0 ; j <= i ; j++) {
if (i == 0 || j == 0)
coef = 1;
else
coef = coef * (i - j + 1) / j;
printf("%4d",coef);
}
printf("\n");
}
}
what I was trying to do:
void PascalTriangle(int rows) {
int i =0,j = 0,space,coef = 0;
for (i = 0 ; i<rows ; i++){
for (space = 1 ; space <= rows - i ; space++)
printf(" ");
for (j = 0 ; j <= i ; j++) {
if (i == 0 || j == 0)
coef ++;
else
coef = coef * (i - j + 1) / j;
printf("%4d",coef);
}
printf("\n");
}
}
When increasing coef my output looks good only on the sides of the triangle:
I would like to clarify - I am not looking for a solution but to learn where I went wrong, I will appreciate any help.
As you ask for directions and not for a solution, I'll say that you cannot use the same index algebra as in the standard Pascal's triangle formula when the outer coefficients aren't equal to one.

This is a c program to find next greatest number with same digits. But not passing one test case

This is a C program to find the next greater number with the same digits. This program is working for all given test cases except one. When the input is 472, the expected output is 724. But my output is 247. Can anyone please help me to find the error?
logic I tried to solve this is :
Traverse the given number from rightmost digit, keep traversing till you find a digit which is smaller than the previously traversed digit. For example, if the input number is 534976, we stop at 4 because 4 is smaller than next digit 9. If we do not find such a digit, then output is Not Possible.
Now search the right side of above found digit ‘d’ for the smallest digit greater than ‘d’. For 534976, the right side of 4 contains 976. The smallest digit greater than 4 is 6.
Swap the above found two digits, we get 536974 in above example.
Now sort all digits from position next to ‘d’ to the end of number. The number that we get after sorting is the output. For above example, we sort digits in bold 536974. We get 536479 which is the next greater number for input 534976.
Here is my code:
#include <stdio.h>
#include <stdlib.h>
int main() {
int N, dig[100], i = 0,j, temp, t, s, k, l, min, temp1;
scanf("%d", &N);
while (N > 0) {
dig[i] = N % 10;
i++;
N = N / 10;
}
for (j = 0; j <= i; j++) {
if (dig[j] > dig[j + 1]) {
s = j;
break;
}
}
min = dig[s];
//printf("%d ", min);
for (k = s; k >= 0; k--) {
if (dig[k] <= min) {
min = dig[k];
t = k;
}
}
//printf("%d ", t);
temp = dig[t];
dig[t] = dig[s + 1];
dig[s + 1] = temp;
for (k = 0; k <= s; k++) {
for (l = k + 1; l <= s; l++) {
if (dig[k] < dig[l]) {
temp1 = dig[k];
dig[k] = dig[l];
dig[l] = temp1;
}
}
}
for (k = i - 1; k >= 0; k--) {
printf("%d", dig[k]);
}
}
Your algorithm seems correct, but the loops are incorrect. Some index boundaries are off by one and the comparisons with <= are incorrect. Storing the digits by increasing powers of 10, while more practical is counter-intuitive and complicates the translation of the algorithm into code.
Here is a corrected version, that outputs all greater numbers. You can easily check the output by piping through sort -c to verify order and wc -l to verify that all combinations have been found (there should be at most n! - 1 greater numbers for a number with n digits).
#include <stdio.h>
int main() {
int N, dig[100], i, j, s, t, k, l, temp;
if (scanf("%d", &N) != 1 || N < 0)
return 1;
for (;;) {
for (i = j = 100; N > 0;) {
dig[--i] = N % 10;
N = N / 10;
}
for (s = j - 2; s >= i; s--) {
if (dig[s] < dig[s + 1]) {
break;
}
}
if (s < i) {
/* no greater number with the same digits */
break;
}
t = s + 1;
for (k = t + 1; k < j; k++) {
if (dig[k] < dig[t] && dig[k] > dig[s]) {
t = k;
}
}
temp = dig[t];
dig[t] = dig[s];
dig[s] = temp;
for (k = s + 1; k < j; k++) {
for (l = k + 1; l < j; l++) {
if (dig[k] > dig[l]) {
temp = dig[k];
dig[k] = dig[l];
dig[l] = temp;
}
}
}
N = 0;
for (k = i; k < j; k++) {
N = N * 10 + dig[k];
printf("%d", dig[k]);
}
printf("\n");
}
return 0;
}
Input: 472
Output:
724
742

Inverse of a binary matrix in C

I have a binary matrix (zeros and ones) D[][] of dimension nxn where n is large (approximately around 1500 - 2000). I want to find the inverse of this matrix in C.
Since I'm new to C, I started with a 3 x 3 matrix and working around to generalize it to N x N. This works for int values, however since I'm working with binary 1's and 0's. In this implementation, I need unsigned int values.
I could find many solutions for int values but I didn't come across any solution for unsigned int. I'd like to find the inverse of a N x N binary matrix without using any external libraries like blas/lapack. It'd be great if anyone could provide a lead on M x N matrix.
Please note that I need inverse of a matrix, not the pseudo-inverse.
/* To find the inverse of a matrix using LU decomposition */
/* standard Headers */
#include<math.h>
#include<stdio.h>
int main() {
/* Variable declarations */
int i,j;
unsigned int n,m;
unsigned int rows,cols;
unsigned int D[3][3], d[3], C[3][3];
unsigned int x, s[3][3];
unsigned int y[3];
void LU();
n = 2;
rows=3;cols=3;
/* the matrix to be inverted */
D[0][0] = 1;
D[0][1] = 1;
D[0][2] = 0;
D[1][0] = 0;
D[1][1] = 1;
D[1][2] = 0;
D[2][0] = 1;
D[2][1] = 1;
D[2][2] = 1;
/* Store the matrix value for camparison later.
this is just to check the results, we don't need this
array for the program to work */
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++) {
C[m][j] = D[m][j];
}
}
/* Call a sub-function to calculate the LU decomposed matrix. Note that
we pass the two dimensional array [D] to the function and get it back */
LU(D, n);
printf(" \n");
printf("The matrix LU decomposed \n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
printf(" %d \t", D[m][j]);
}
printf("\n");
}
/* TO FIND THE INVERSE */
/* to find the inverse we solve [D][y]=[d] with only one element in
the [d] array put equal to one at a time */
for (m = 0; m <= rows-1; m++) {
d[0] = 0;
d[1] = 0;
d[2] = 0;
d[m] = 1;
for (i = 0; i <= n; i++) {
x = 0;
for (j = 0; j <= i - 1; j++){
x = x + D[i][j] * y[j];
}
y[i] = (d[i] - x);
}
for (i = n; i >= 0; i--) {
x = 0;
for (j = i + 1; j <= n; j++) {
x = x + D[i][j] * s[j][m];
}
s[i][m] = (y[i] - x) / D[i][i];
}
}
/* Print the inverse matrix */
printf("The Inverse Matrix\n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
printf(" %d \t", s[m][j]);
}
printf("\n");
}
/* check that the product of the matrix with its iverse results
is indeed a unit matrix */
printf("The product\n");
for (m = 0; m <= rows-1; m++) {
for (j = 0; j <= cols-1; j++){
x = 0;
for (i = 0; i <= 2; i++) {
x = x + C[m][i] * s[i][j];
}
//printf(" %d %d %f \n", m, j, x);
printf("%d \t",x);
}
printf("\n");
}
return 0;
}
/* The function that calcualtes the LU deomposed matrix.
Note that it receives the matrix as a two dimensional array
of pointers. Any change made to [D] here will also change its
value in the main function. So there is no need of an explicit
"return" statement and the function is of type "void". */
void LU(int (*D)[3][3], int n) {
int i, j, k;
int x;
printf("The matrix \n");
for (j = 0; j <= 2; j++) {
printf(" %d %d %d \n", (*D)[j][0], (*D)[j][1], (*D)[j][2]);
}
for (k = 0; k <= n - 1; k++) {
for (j = k + 1; j <= n; j++) {
x = (*D)[j][k] / (*D)[k][k];
for (i = k; i <= n; i++) {
(*D)[j][i] = (*D)[j][i] - x * (*D)[k][i];
}
(*D)[j][k] = x;
}
}
}
This is just a sample example that I tried and I have -1 values in the inverse matrix which is my main concern. I have 1000 x 1000 matrix of binary values and the inverse should also be in binary.
The matrix:
1 1 0
0 1 0
1 1 1
The matrix LU decomposed:
1 1 0
0 1 0
1 0 1
The Inverse Matrix:
1 -1 0
0 1 0
-1 0 1
The product:
1 0 0
0 1 0
0 0 1

Minesweeper revealing cells in C

I am trying to write a minesweeper program in C.
What I am trying to achieve here is when user steps on one cell, the cells near without bombs and hint numbers will be revealed.
For example, if x is the cell stepped on, o is an empty but concealed square, . is an empty but revealed cell and * is the bomb (hidden when playing of course):
x o o o o
o o o * o
o o o o o
will result in:
. . 1 o o
. . 1 * o
. . 1 o o
Here is part of the code:
while (1)
{
printf("Row? ");
scanf("%d", &row);
printf("column? ");
scanf("%d", &clos);
if (row < 9 && row >= 0 && clos < 8 && clos >= 0)
break;
printf("\nInvalid Location\n\n");
}
if (real_map[row][clos] =='*')
{
print_map_win(display_map,real_map);
printf("\n");
printf("Flags Left = %d\n\n\n", flag_left);
printf("Game Over\n");
exit(0);
}
else
{
if (real_map[row][clos] == ' ')
{
display_map[row][clos] = real_map[row][clos];
bonos_reveal(display_map, real_map, clos, row);
// [[[bonos_reveal is the function I am asking for]]]
printf("\n");
}
else
{
display_map[row][clos] = real_map[row][clos];
}
}
in which real_map has the hint number and bombs in it, and display_map is the current state of the map.
edit: I have the following code, and it only reveals in one direction:
int bonos_reveal(int disp_map[MAP_ROWS][MAP_COLS], int real_map[MAP_ROWS][MAP_COLS], int clos, int row)
{
disp_map[row][clos] = real_map[row][clos];
if (row < 9 && row >= 0 && clos < 8 && clos >= 0)
{
if (real_map[row][clos+1] == ' ')
{
bonos_reveal(disp_map, real_map, clos + 1, row);
}
else
{
disp_map[row][clos+1] = real_map[row][clos+1];
return 1;
}
}
else
{
return 1;
}
return 1;
}
I have no idea how to loop through the cells.
Okay, here's an example implementation. It uses the following values for tiles:
0 to 8: an unmined tile; the number represents the pre-calculated number of adjacent mines
9: a mine; this special value is defined as BOMB.
Covered tiles have 10 added to that, flagged tiles (not used here) have 20 added to that. You can test whether a tile is mined with:
board[row][col] % 10 == BOMB
I'll let the code do the explaining:
#include <stdlib.h>
#include <stdio.h>
#include <time.h>
#define ROWS 12
#define COLS 20
#define BOMBS 8
#define BOMB 9
void inc(int board[ROWS][COLS], int row, int col)
{
if (row < 0 || row >= ROWS) return;
if (col < 0 || col >= COLS) return;
if (board[row][col] % 10 == BOMB) return;
board[row][col]++;
}
/*
* Set up board and pre-calculate adjacent bombs
*/
void board_init(int board[ROWS][COLS])
{
int i, j, n;
for (j = 0; j < ROWS; j++) {
for (i = 0; i < COLS; i++) {
board[j][i] = 10;
}
}
n = 0;
while (n < BOMBS) {
j = rand() % ROWS;
i = rand() % COLS;
if (board[j][i] % 10 != BOMB) {
board[j][i] = 19;
inc(board, j - 1, i - 1);
inc(board, j - 1, i);
inc(board, j - 1, i + 1);
inc(board, j, i - 1);
inc(board, j, i + 1);
inc(board, j + 1, i - 1);
inc(board, j + 1, i);
inc(board, j + 1, i + 1);
n++;
}
}
}
/*
* Reveal tile and propagate revelation
*/
void board_reveal(int board[ROWS][COLS], int row, int col)
{
if (row < 0 || row >= ROWS) return; /* skip off-board tiles */
if (col < 0 || col >= COLS) return;
if (board[row][col] < 10) return; /* already revealed, skip */
if (board[row][col] >= 20) return; /* must remove flag first, skip */
if (board[row][col] % 10 == BOMB) {
int i, j;
printf("Bang!\n");
for (j = 0; j < ROWS; j++) {
for (i = 0; i < COLS; i++) {
if (board[j][i] % 10 == BOMB) board[j][i] = BOMB;
}
}
} else {
board[row][col] %= 10;
if (board[row][col] == 0) {
board_reveal(board, row - 1, col);
board_reveal(board, row, col - 1);
board_reveal(board, row, col + 1);
board_reveal(board, row + 1, col);
}
}
}
void board_print(int board[ROWS][COLS])
{
int i, j;
for (j = 0; j < ROWS; j++) {
putchar(' ');
for (i = 0; i < COLS; i++) {
const char *tile = ".12345678*##########PPPPPPPPPP";
int k = board[j][i];
putchar(tile[k]);
}
putchar('\n');
}
}
int main()
{
int board[ROWS][COLS];
srand(time(NULL));
board_init(board);
board_reveal(board, 0, 0);
board_print(board);
return 0;
}

Sub Grouping algorithm

Recently, someone asked me to make a C program that "groups" (his words, not mine!) numbers into pairs.
Here's how it works.
First, the user inputs the maximum range:(let's say) 10
Now, user inputs a number: (let's say) 4.
Then, the program groups 4 and 5 together. (ie. n and n+1)
Next User Input: 8
The program groups 8 and 9 as well.
Now, this goes on.
Exceptions: If the user enters a number that has already been grouped, like 4,5,8 or 9. Then the group which it belongs to gets removed altogether. Also, the program invalidates inputs that require pairing with numbers that are already paired. Eg. If 4 and 5 are paired, 3 is not a valid input.
Also, entering the extremes (here, 1 and 10) is not allowed.
I made the above program in C, using Visual Studio 2013. I have provided the code below.
My questions are:
A) How could I have made my code considerably better?(Apart from initializing the array AFTER accepting the max input)
B) More importantly, can someone tell me what this algorithm is? Is this a standard problem? Does it have any real world application/implementation? Or is it just some random idea?
#include<stdio.h>
#inlcude<conio.h>
#define array_size 10
int group[array_size][2] = { 0 };
int n = 0, max=0, search = 0, max_mem = 0;
int tcount = 2;
void sort(int x[][2]);
void print_groups();
void test_print();
void main()
{
group[0][0] = 0;
group[0][1] = 1;
printf("Enter a number:");
scanf_s("%d", &max);
max_mem = (max/2)+1;
if (max_mem > array_size)
{
printf("Not enough memory assigned!");
return;
}
else
{
group[max_mem-1][0] = max;
}
print_groups();
test_print();
while (1)
{
printf("Enter a number:");
scanf_s("%d", &n);
if ((n <= 1) || (n >= max-1))
{
printf("Invalid entry!");
continue;
}
search = 0;
for (int i = 1; i < max_mem; i++)
{
for (int j = 0; ((j < 2)&&(search!=1)); j++)
{
if (n == group[i][j])
{
group[i][0] = 0;
group[i][1] = 0;
search = 1;
}
if (group[i][0]==n+1)
{
printf("Already group exists -> (%d,%d)", group[i][0], group[i][1]);
//getch();
search = 1;
}
}
}
if (search != 1)
{
group[1][0] = n;
group[1][1] = n + 1;
}
printf("\nSorting!\n");
sort(group);
//clrscr();
print_groups();
test_print();
}
}
void sort(int x[][2])
{
int i, j, t[1][2];
for (i = 1; i <= max_mem - 2; i++)
for (j = 2; j <= max_mem-1 - i; j++)
if (x[j - 1][0] >= x[j][0])
{
t[0][0] = x[j - 1][0];
x[j - 1][0] = x[j][0];
x[j][0] = t[0][0];
t[0][1] = x[j - 1][1];
x[j - 1][1] = x[j][1];
x[j][1] = t[0][1];
}
}
void print_groups()
{
printf("The group is:\n%d ", group[0][1]);
for (int i = 1; i < max_mem-1; i++)
{
if (group[i][0] != 0)
{
printf("(");
printf("%d,", group[i][0]);
printf("%d", group[i][1]);
printf(")");
}
}
printf(" %d.", group[max_mem - 1][0]);
printf("\n");
}
void test_print()
{
printf("Array Formation:\n");
for (int i = 0; i < array_size; i++)
{
printf(" %d,%d ", group[i][0], group[i][1]);
}
printf("\n");
}
Sounds like it's just some random idea. You can simplify your code by using a one-dimensional array, where each entry in the array is
0 for numbers not in a group
1 for the first number of a group
2 for the second number of a group
For example, if array[4] is 1 and array[5] is 2, then 4 and 5 are a group.
When the user enters a new number, it's easy to update the array. Here's an example in pseudo-code of how the array would be updated if the user enters the number 7
if (array[7] == 0 and array[8] == 0)
array[7] = 1, array[8] = 2
else if (array[7] == 0 and array[8] == 1)
input is invalid
else if (array[7] == 1)
array[7] = 0, array[8] = 0
else if (array[7] == 2)
array[6] = 0, array[7] = 0

Resources