Celebrity using stack in C language - c

For this question you have to take a 2D array or matrix and using Stack function push and pop , find the celebrity member in the matrix. Only using C language
Here is my code that I have tried
#include <stdio.h>
#define size 4
int stack[size];
int top=-1;
void push(int val){
if(top==size-1){
printf("stack is already full,error\n");
}else{
top++;
stack[top]=val;
}
}
int pop(){
if(top==-1)
{
printf("underflow condition");
}
else{
return stack[top--];
}
}
int CelebrityProblem(int arr[4][4])
{
int i;
for ( i = 0; i<4; i++)
push(i);
while (size>1)
{
int temp1 =stack[top];
pop();
int temp2 = stack[top];
pop();
if (arr[temp1][temp2])
push(temp2);
else
push(temp1);
}
int potential_celeb=stack[top];
int j;
for( j=0; j<4; j++)
{
if(j==stack[top])
continue;
if(arr[potential_celeb][j]==1)
return -1;
if(arr[j][potential_celeb]!=1)
return -1;
}
return potential_celeb;
}
int main(){
int arr[4][4]={ {0,0,1,1},
{1,0,1,0},
{0,1,0,0},
{0,1,1,0} };
int celebrity = CelebrityProblem(arr);
if(celebrity == -1)
printf("No Celebrity Exists!");
else
printf("Celebrity is Person Number %d",celebrity);
return 0;
}
According to my approach I am getting output as conditionunderflow . can anyone please help me to find where i'm doing the mistake .

Related

How can I Implement an average of integers stored in a given stack using C? I have the main and average code but I Can't combine them with each other

This is a question in the DSA course.
This is the main code.
#include <stdio.h>
#include <stdlib.h>
#define SIZE 5
int stack[SIZE], t;
void stack_init(void);
void pop(void);
int top(void);
int empty(void);
int push(int x);
int main() {
int i;
int loop = 1;
stack_init();
while (loop == 1) {
scanf("%d", & i);
if (i == 0) {
if (empty())
printf("Error - Stack is empty\n");
else
pop();
} else if (i < 0) {
if (empty())
printf("Error - Stack is empty\n");
else
printf("%d\n", top());
} else
if(push(i)==0)
{
printf("Stack is full\n");
}
}
}
//****************************************************
// Implement the calcualte average here
//****************************************************
//function to check the array is full
int is_full()
{
//if T is equal to size
if(t==SIZE-1)
{
return 1;
}
return 0;
}
void stack_init(void) {
t = -1;
}
//variation of push which returns true and false
int push(int x)
{
//if array is full
if(is_full())
return 0;
//otherwise push the element
t = t + 1;
stack[t] = x;
//return success
return 1;
}
void pop(void) {
t = t - 1;
}
int top(void) {
return stack[t];
}
int empty(void) {
return t == -1;
}```
What I want is calculate the average of integers stored in a given stack.
the stack must be in its original form. I can use temporary data structures during the operation.
And this is the average code that I want to Implement.
double average;
CreateStack(&stack);
while (!StackFull(&stack)) {
Push(val, &stack); }// push value on to stack
while (!StackEmpty(&stack)) {
average += Pop(&stack); } // pop value from stack
average = average / StackFull(&stack); // calculate average
while (!StackEmpty(&stack)) {
Push(Pop(&stack), &stack);} // put values back on stack
return average;
Please help to to find the answer of this question.

Hanoi Tower Problem using stacks - It is not solving the hanoi problem but moving the disks

//Stack Study by yoonseul at 210719
#include <stdio.h>
#include <stdbool.h>
#define SIZE 9
#define _CRT_SECURE_NO_WARNINGS
typedef struct {
int item[SIZE];
int top;
} Stack;
void InitStack(Stack* pstack)
{
pstack->top = -1;
}
bool IsFull(Stack* pstack)
{
return pstack->top == SIZE - 1;
}
bool IsEmpty(Stack* pstack)
{
return pstack->top == -1
}
int Peek(Stack* pstack)
{
if (IsEmpty(pstack)) {
return -1;
}
return pstack->item[pstack->top];
}
void Push(Stack* pstack, int disk)
{
if (IsFull(pstack)) {
exit(1);
}
pstack->item[++(pstack->top)] = disk;
}
void Pop(Stack* pstack) {
if (IsEmpty(pstack)) {
exit(1);
}
--(pstack->top);
}
int exchange(int x);
int main()
{
int num;
int rod[3][SIZE];
char from='0', to;
int move;
scanf("%d", &num);
InitStack(&rod[0]);
InitStack(&rod[1]);
InitStack(&rod[2]);
for (int i = 0; i < num+1; i++) {
Push(&rod[0], i+1);
Push(&rod[1], 0);
Push(&rod[2], 0);
}
while (from != 'q') {
printf("%3c %3c %3c\n", 'A', 'B', 'C');
for (int i = 0;i<num; i++) {
printf("%3d %3d %3d\n", rod[0][i], rod[1][i], rod[2][i]);
}
scanf("%c %c", &from, &to);
if (from == 'q')
return 0;
int peekF, peekT;
int numF = exchange(from);
int numT = exchange(to);
peekF = Peek(&rod[numF]);
peekT = Peek(&rod[numT]);
if (peekF > peekT && peekT != -1) {
printf("Invalid Move");
}
else {
Pop(&rod[numF]);
Push(&rod[numT],peekF);
}
}
}
int exchange(int x)
{
switch (x) {
case 'A':
return 0;
case 'B':
return 1;
case 'C':
return 2;
}
}
Here is my full code for Hanoi Problem.
The objective is to make a problem that can move this between the rod, and print 'invalid move' if the move is invalid. Also, user can input the number of the disks.
When I debug, there are two errors occur.
One is beneath ' A B C' the last number disk is printed three times. My objective is to print ' 1 0 0'
(ex. if maximum disk is 3,' 3 3 3' is printed.)
edited I solved the first one.
for (int i = 0; i < num + 1; i++) {
Push(&rod[0], i+1);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[1], 0);
}
for (int i = 0; i < num + 1; i++) {
Push(&rod[2], 0);
}
I changed disk putting part like like using for statement three times. but I don't know the reason why this happens.
Edited
The hanoi Tower is printed twice, after 2nd scan. I want to know the reason why this happens. It seems like memory problem. I want to know why. I'm new to coding.
PLZ help me. I'm crying.

evaluate a polyome for a given value

I wanted to evaluate a polynome for a given value so I have used a linked list to store the coefficients and the exponants,and I have defined a function evaluate() to evaluate the polynome for a given value, but I do have a problem when it comes to the output it always shows the value 0.00000
can I get some help ? thanks in advance.
here's the full code :
#include <stdio.h>
#include <stdlib.h>
typedef struct list
{
int coef;
int expo;
struct list* next;
}list;
int compare(char* s1,char* s2)
{
int i=0;
char c1,c2;
do
{
c1= (*(s1+i));
c2= (*(s2+i));
i++;
if(c2 == '\0' || c1 == '\0')
return c1-c2;
}while(c1==c2);
return c1-c2;
}
int transform(char* arr)
{
int i,sign=0;
int s=0;
if((*arr) == '-') sign=1;
for(i=0;arr[i]!='\0';i++)
{
if(arr[i]>=0 && arr[i]<=9)
s=s*10+(arr[i]-'0');
}
if(sign) return -s;
return s;
}
list* insert(list* head,char* coef,int expo)
{
list* node=(list*)malloc(sizeof(list));
if(node==NULL)
{
printf("Stack Overflow");
exit(1);
}
node->next=NULL;
node->coef=transform(coef);
node->expo=expo;
if(head==NULL) return node;
list* temp=head;
while(temp && temp->next)
temp=temp->next;
temp->next=node;
return head;
}
float power_of(float x,int expo)
{
if(expo==0) return 1;
int i=1;
float s=1;
if(expo > 0)
while(i++ <= expo)
s*=x;
else if (expo < 0)
while(i++ <= -expo)
s*=1.0/x;
return s;
}
float evaluate(list* head,float x)
{
if(head==NULL) return 0;
float s=0.0;
while(head)
{
s+=(head->coef)*power_of(x,head->expo);
head=head->next;
}
return s;
}
int main()
{
list* head=NULL;
char coef[11];
int expo,i=1;
float x;
printf("insert the polynome <type end to stop>:\n");
do
{
printf("insert the coefficient %d> : ",i);
scanf("%s",coef);
if(compare(coef,"end"))
{
printf("insert the exposnant %d> : ",i++);
scanf("%d",&expo);
head=insert(head,coef,expo);
}
}while(compare(coef,"end"));
printf("insert a value to evaluate the polynome : ");
scanf("%f",&x);
float value=evaluate(head,x);
printf("output : %f ",value);
return 0;
}

Parenthesis balance program crashing(c)

Good afternoon, i am trying to do a program that checks whether if a expression has its parentheses balanced or not but because of some problem that i can't quite find out the program is crashing, could somebody help me find a way so that the program works?
In
a * b - (2 + c)
Out
Correct
or
In
)3+b * (2-c)(
Out
Incorrect
The program should check only for parantheses and i am supposed to implement linear lists on the code.
#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define SUCESSO 1 //Succes
#define FALHA -1 //Failure
#define CELULA_INVALIDA 0 //Invalid key
#define TAMANHO_MAXIMO 1000 //Max size
typedef struct{
char exp[1000];
unsigned int chave; //key
}celula; //node
typedef struct{
celula celulas[TAMANHO_MAXIMO]; //vector of nodes
unsigned int tamanho; //size of the list
}fila; //list
int criarFilaVazia(fila * ent){ //create an empty list
ent->tamanho = 0;
return(SUCESSO);
}
int insFinal(fila * ent, celula node){ //put a node on the end of the list
unsigned int i;
celula aux;
if(ent->tamanho == TAMANHO_MAXIMO){
return(FALHA);
}
else{
ent->celulas[ent->tamanho] = node;
ent->tamanho++;
return(SUCESSO);
}
}
void mostrarCelula(celula ent){ //show node
printf("%s \n", ent.exp);
}
void mostrarFila(fila ent){ //show entire list
unsigned int i;
if(ent.tamanho == 0){
printf("Fila vazia");
}
else{
printf("A fila possui %u element \n", ent.tamanho);
for(i=0; (i < ent.tamanho); i++){
printf("Elemento %u \n \n", (i+1));
mostrarCelula(ent.celulas[i]);
}
}
}
int main(){
int i, j;
fila exp;
celula aux;
scanf("%s", &aux.exp);
getchar();
aux.chave = 0;
insFinal(&exp, aux);
for(i = 0; i < strlen(exp.celulas[0].exp); i++){//checks all the array
if(exp.celulas[0].exp[i] == '('){//if there is an opening
for(j = i; j < strlen(exp.celulas[0].exp); j++){
if(exp.celulas[0].exp[j] == ')'){//should be and ending
exp.celulas[0].exp[i] = 0;//removes if balanced
exp.celulas[0].exp[j] = 0;
}
}
}
}
//checks for remaining parentheses and prints the output
for(i = 0; i < strlen(exp.celulas[0].exp); i++){
if(exp.celulas[0].exp[i] == '(' || exp.celulas[0].exp[i] == ')'){
printf("Incorreta"); //incorrect
}
else{
printf("Correta"); //correct
}
}
return 0;
}
[enter image description here][1]
Error message: https://i.stack.imgur.com/aeSn5.png
it says ex06 stopped working
Your program is crashing inside insFinal because the ent parameter passed in from main has uninitialized data. Hence, undefined behavior. Ammend these two lines at the beginning of main:
fila exp;
celula aux;
With this:
fila exp = {0};
celula aux = {0};
That will zero-init both.
The thing I don't get is what all these data structures are used for. Nor do I understand the double-nested for loop for checking the balance. Checking for a balanced set of parentheses in an expression should be as simple as this:
int areParenthesesBalanced(const char* str)
{
int balance = 0;
int len = str ? strlen(str) : 0;
for (int i = 0; i < len; i++)
{
if (str[i] == '(')
{
balance++;
}
else if (str[i] == ')')
{
balance--;
if (balance < 0)
{
return 0;
}
}
}
return (balance == 0) ? 1 : 0;
}
int main() {
char str[1000];
scanf("%s", str);
if (areParenthesesBalanced(str))
{
printf("Incorreta\n");
}
else
{
printf("Correta\n");
}
return 0;
}

Sparse Matrix with linked lists

I'm trying to create a sparse matrix in C using linked lists. My professor gave the file.h structs, a list of the functions and what they should do and told us to "work with it".
To resume everything, my code does not work, it stops working when I try to insert an element (calling ins_elem()) and returning weird number when calling soma_elem_coluna() and soma_elem_linha().
I've put the whole code below but the issue is really within the functions specified above (and soma_const() as I can't test it without inserting an element).
The logic I used is to create a matrix as in the image below (with numbers instead of characters)
[
Don't mind the weird typing, some words are in Portuguese.
(C = column and L = row)
this is my file.h:
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define LINES 4
#define COLUM 4
typedef struct Node{
int Val, L, C;
struct Node *down, *right;
}Node;
typedef struct{
Node *L[LINES], *C[COLUM];
}matriz;
void cria_matriz(matriz* m); // creates matrix
void ins_elem(matriz* m, int e, int l, int c); // insert element e into lxc
void soma_const(matriz* m, int e, int l, int c); // add value e to existing lxc
int soma_elem_linha(matriz *m, int l); // sums all the values in row l
int soma_elem_coluna(matriz *m, int c); // sums all the values in column c
void imp(matriz *m); // prints the matrix
my file.c
#include "file.h"
void cria_matriz(matriz* m)
{
int i;
for(i=0;i<LINES;i++) //initializes headrows
{
m->L[i]->down = NULL;
m->L[i]->right = NULL;
m->L[i]->C = -1;
m->L[i]->L = -1;
}
for(i=0;i<COLUM;i++) //initializes headcolumns
{
m->C[i]->down = NULL;
m->C[i]->right = NULL;
m->C[i]->C = -1;
m->C[i]->L = -1;
}
}
void ins_elem(matriz *m, int e, int l, int c)
{
Node* auxLine; // move through row
Node* auxCol; // move through column
auxLine = &m->L[l];
auxCol = &m->C[c];
while(auxLine->right != NULL && auxLine->right->C < c) //find correct pos in row
{
auxLine = auxLine->right;
}
while(auxCol->down != NULL && auxCol->down->L < c) //find correct pos in column (error happens here)
{
auxCol = auxCol->down;
}
Node* novo = malloc(sizeof(Node));
novo->Val = e;
novo->C = c;
novo->L = l;
novo->down = auxCol->down;
auxCol->down = novo;
novo->right = auxLine->right;
auxLine->right = novo;
}
void soma_const(matriz *m, int e, int l, int c)
{
Node* aux = &m->C[c];
while(aux->down != NULL && aux->L < l)
aux = aux->down;
aux->Val+=e;
}
int soma_elem_coluna(matriz *m, int c)
{
int sum = 0;
Node* aux = &m->C[c];
if(aux->down == NULL)
return 0;
while(aux->down != NULL)
{
aux = aux->down;
sum += aux->Val;
}
return sum;
}
int soma_elem_linha(matriz *m, int l)
{
int sum = 0;
Node* aux = &m->L[l];
if(aux->right == NULL)
return 0;
while(aux->right != NULL)
{
aux = aux->right;
sum += aux->Val;
}
return sum;
}
void imp(matriz *m)
{
Node* aux;
int i, j;
for(i=0;i<LINES;i++)
{
aux = &m->L[i];
for(j=0;j<COLUM;j++)
{
if(aux->C == j)
{
printf("%d ",aux->Val);
aux = aux->right;
}
else
{
printf("0 ");
}
}
printf("\n");
}
}
my main.c:
#include "file.h"
int main()
{
struct matriz* M = (matriz*)malloc(sizeof(matriz));
int i,e,c,l,result;
char str[20];
for(i=0;i<5;i++) // this is temporary and another issue, how I make a while that
{ // only stops when user (a bot actually) presses enter?
scanf(" %s",str);
if(!strcmp(str,"cria_matriz"))
{
cria_matriz(M);
}
else if(!strcmp(str,"ins_elem"))
{
scanf("%d %d %d",&e,&l,&c);
ins_elem(M,e,l,c);
}
else if(!strcmp(str,"soma_const"))
{
scanf("%d %d %d",&e,&l,&c);
soma_const(M,e,l,c);
}
else if(!strcmp(str,"soma_elem_linha"))
{
scanf("%d",&l);
result = soma_elem_linha(M,l);
printf("%d\n",result);
}
else if(!strcmp(str,"soma_elem_coluna"))
{
scanf("%d",&c);
result = soma_elem_coluna(M,c);
printf("%d\n",result);
}
else if(!strcmp(str,"imp"))
{
imp(M);
}
}
return 0;
}
Your files didn't compile without warnings as there were lots of pointer and other problems with the code. I've worked over your code to clean up the warnings but I'm not in a position to test the logic -- you'll have to do that:
file.c
#include "file.h"
void cria_matriz(matriz *m)
{
for (int i = 0; i < LINES; i++) // initializes headrows
{
m->L[i] = malloc(sizeof(Node));
m->L[i]->down = NULL;
m->L[i]->right = NULL;
m->L[i]->C = -1;
m->L[i]->L = -1;
m->L[i]->Val = 0;
}
for (int i = 0; i < COLUM; i++) // initializes headcolumns
{
m->C[i] = malloc(sizeof(Node));
m->C[i]->down = NULL;
m->C[i]->right = NULL;
m->C[i]->C = -1;
m->C[i]->L = -1;
m->C[i]->Val = 0;
}
}
void ins_elem(matriz *m, int e, int l, int c)
{
Node *auxLine = m->L[l]; // move through row
Node *auxCol = m->C[c]; // move through column
while (auxLine->right != NULL && auxLine->right->C < c) // find correct pos in row
{
auxLine = auxLine->right;
}
while (auxCol->down != NULL && auxCol->down->L < c) // find correct pos in column (error happens here)
{
auxCol = auxCol->down;
}
Node *novo = malloc(sizeof(*novo));
novo->Val = e;
novo->C = c;
novo->L = l;
novo->down = auxCol->down;
auxCol->down = novo;
novo->right = auxLine->right;
auxLine->right = novo;
}
void soma_const(matriz *m, int e, int l, int c)
{
Node *aux = m->C[c];
while (aux->down != NULL && aux->L < l)
{
aux = aux->down;
}
aux->Val += e;
}
int soma_elem_coluna(matriz *m, int c)
{
Node *aux = m->C[c];
if (aux->down == NULL) {
return 0;
}
int sum = 0;
while (aux->down != NULL)
{
aux = aux->down;
sum += aux->Val;
}
return sum;
}
int soma_elem_linha(matriz *m, int l)
{
Node *aux = m->L[l];
if (aux->right == NULL) {
return 0;
}
int sum = 0;
while (aux->right != NULL)
{
aux = aux->right;
sum += aux->Val;
}
return sum;
}
void imp(matriz *m)
{
for (int i = 0; i < LINES; i++)
{
Node *aux = m->L[i];
for (int j = 0; j < COLUM; j++)
{
if (aux->C == j)
{
printf("%d ", aux->Val);
aux = aux->right;
}
else
{
printf("0 ");
}
}
printf("\n");
}
}
main.c
#include "file.h"
int main()
{
matriz *M = malloc(sizeof(*M));
int e, c, l;
char str[32];
for (int i = 0; i < 5; i++) // this is temporary and another issue, how I make a while that
{ // only stops when user (a bot actually) presses enter?
(void) scanf(" %s", str);
if (strcmp(str, "cria_matriz") == 0)
{
cria_matriz(M);
}
else if (strcmp(str, "ins_elem") == 0)
{
scanf("%d %d %d", &e, &l, &c);
ins_elem(M, e, l, c);
}
else if (strcmp(str, "soma_const") == 0)
{
(void) scanf("%d %d %d", &e, &l, &c);
soma_const(M, e, l, c);
}
else if (strcmp(str, "soma_elem_linha") == 0)
{
(void) scanf("%d", &l);
int result = soma_elem_linha(M, l);
printf("%d\n", result);
}
else if (strcmp(str, "soma_elem_coluna") == 0)
{
scanf("%d", &c);
int result = soma_elem_coluna(M, c);
printf("%d\n", result);
}
else if (strcmp(str,"imp") == 0)
{
imp(M);
}
}
free(M);
return 0;
}
The biggest issue was that you kept making pointers to things that were already pointers. Also, you initialized data that you hadn't actually allocated. You didn't initialize some data that you subsequently added onto. Finally, strcmp() isn't a boolean, don't use it as one.

Resources