I'm Recently going through Divide and Conquer Algorithm.
I'm able to solve the problems if the return value supposes to be some single integer.
Ex:1. Binary Search, here I just need to return 1 if found, else -1.
Ex:2. Maximum Number in an array, just need to return a single number.
But when it comes to returning an array, like when we need the whole array as output(Ex: Sorting).
I feel it difficult.
Can anyone help with the best approach?
Below is my approach for Binary Search.
#include<stdio.h>
char* Divide(int arr[],int l,int r,int key)
{
int m=(l+r)/2;
if(l==r)
{
if(key==arr[m])
return "Found";
else
return "Not Found";
}
else
{
if(key==arr[m])
return "Found";
else if(key>arr[m])
Divide(arr,m+1,r,key);
else
Divide(arr,l,m,key);
}
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8};
int n=sizeof(arr)/sizeof(arr[0]);
char* result=Divide(arr,0,n-1,10);
printf("%s\n",result);
return 0;
}
you would have to return the values in your recursive call try
#include<stdio.h>
char* Divide(int arr[],int l,int r,int key)
{
int m=(l+r)/2;
if(l==r)
{
if(key==arr[m])
return "Found";
else
return "Not Found";
}
else
{
if(key==arr[m])
return "Found";
else if(key>arr[m])
return Divide(arr,m+1,r,key); // just returning values here
else
return Divide(arr,l,m,key); // and here would make it work
}
}
int main()
{
int arr[]={1,2,3,4,5,6,7,8};
int n=sizeof(arr)/sizeof(arr[0]);
char* result=Divide(arr,0,n-1,10);
printf("%s\n",result);
return 0;
}
check the demo at online compiler
Related
I am trying to write a program where i implement stacks with arrays and use them to check if a given string has balanced parentheses.
For ex. if inputted '(()){}[()]' ,program would output 'Balanced', otherwise if inputted '({})[' the program would output 'Not balanced'.
This part is the array implementation of the stack.
#include <stdio.h>
#include <stdlib.h>
#define MAX 50
int stack[MAX];
int top=-1;
void push(char val){
if(top==MAX-1){
printf("stack is already full,error\n");
}else{
top++;
stack[top]=val;
}
}
char pop(){
if(top==-1){
printf("not enough elements,error\n");
exit(1);
}else{
top--;
return stack[top];
}
}
This part is the implementation of a common method to solve the problem.
int isMatching(char c1, char c2){
if(c1=='{' && c2=='}')
return 1;
else if(c1 =='(' && c2==')')
return 1;
else if(c1=='[' && c2==']')
return 1;
return 0;
}
int isBalanced(char str[]){
int i=0;
while(str[i]!='\0'){
if(str[i]=='{' || str[i]=='[' || str[i]=='('){
push(str[i]);
}
if(str[i]==')' || str[i] == ']' || str[i]=='}'){
if(stack==NULL){
return 0;
}
if(!isMatching(pop(), str[i])){
return 0;
}
}
i++;
}
if(stack==NULL){
return 1; // balanced parenthesis
}else{
return 0; // not balanced parenthesis
}
}
And this is the main function where the user inputs a string and it's tested if it's 'Balanced' or not.
int main(){
char str[MAX];
int flag;
printf("Enter the string with the brackets and etc.\n");
fgets(str, sizeof(str),stdin);
flag=isBalanced(str);
if(flag==1){
printf("Balanced\n");
}
else{
printf("Not balanced\n");
}
return 0;
}
When i input a very simple example, i get a wrong answer, for instance
Enter the string with the brackets and etc.
()
Not balanced
This is supposed to output 'Balanced' instead.I don't understand how this could have occured.
in pop(), you are decrementing before returning the top element. Change:
top--;
return stack[top];
to
return stack[top--];
Also, in isBalanced(), stack is NEVER null, so delete:
if(stack==NULL){
return 0;
}
and change the balanced check to look for the empty stack from:
if(stack==NULL){
return 1; // balanced parenthesis
}else{
return 0; // not balanced parenthesis
}
To:
if(top==-1){
return 1; // balanced parenthesis
}else{
return 0; // not balanced parenthesis
}
After making these changes, your code appeared to work on my box. This isn't quite how I'd have coded it, but this is the minimal set of changes to make it work.
if (stack==NULL) is the problem here, stack will never be NULL.
You need to check if there are still elements in your stack, by verifying that top > 0
You implemented the push/pop combo wrong. If you push one character top becomes 0. If you popping it immediately it finally executes top--; return stack[top], which evaluates to stack[-1].
Try this push/pop:
int top=-1; //idx to be popped next; <0 -> invalid
void push(char val)
{
if(top==MAX-2)
printf("stack is already full,error\n");
else
stack[++top]=val;
}
char pop()
{
if(top<0) return '\0'; //no abort, just return invalid char
return stack[top--];
}
The answer to your question has already been satisfactorily answered, but as a suggestion for a different approach, consider the following.
Since there are only a very small number of common enclosures used within C source code you can easily track pairs of them using an increment-decrement counter. The following uses a struct, typedefed to balanced_s which is encapsulated into a function to simplify the evaluation. Following is a sample implementation:
typedef struct {
int paren;
int curly;
int square;
bool bBal
}balanced_s;
balanced_s * balanced_enclosures(const char *source);
int main(void)
{
char in[5000] = {0};//you could improve this by reading file size
//first then creating array sized accordingly
FILE *fp = fopen("C:\\play\\source.c", "r");//using copy of this source to test
if(fp)
{
size_t bytes = fread(in, 1, sizeof(in), fp);
}
balanced_s * b = balanced_enclosures(in);
bool balanced = b->bBal;//If not true, inspect the rest of the
//members to see where the imbalance has occurred.
free(b);
return 0;
}
balanced_s * balanced_enclosures(const char *source)
{
balanced_s *pBal = malloc(sizeof(*pBal));
memset(pBal, 0, sizeof(*pBal));
while(*source)
{
switch(*source) {
case '(':
pBal->paren++;
break;
case ')':
pBal->paren--;
break;
case '{':
pBal->curly++;
break;
case '}':
pBal->curly--;
break;
case '[':
pBal->square++;
break;
case ']':
pBal->square--;
break;
}
source++;
pBal->bBal = (!pBal->paren && !pBal->curly && !pBal->square);
}
return pBal;
}
This function aims to return the number of zeroes in a number, num. The function rCountZeros2() passes the result through
the pointer parameter result.
`
void rCountZeros2(int num, int *result)
{
if (num==0)
return;
else
{
if (num%10==0){
(*result)++;
}
rCountZeros2(num/10, result);
}
}
`
See when you are invoking rCountZeros2() , my guess is value in variable result is not zero.It may be some garbage value or some other value from previous computation.However with details you have provided it is difficult to provide exact answer.
Kindly try the following standalone program, I got correct answer using your code
void rCountZeros2(int num, int *result)
{
if (num==0)
return;
else
{
if (num%10==0){
(*result)++;
}
rCountZeros2(num/10, result);
}
}
int main()
{
int result = 0;
int num=12300000;
rCountZeros2(num, &result);
printf("number of zeros in %d = %d",num ,result);
}
I have tried all possible test cases for this SPOJ question that I came across, but still my code is not getting accepted. Can't identify which test case it is failing.
I have considered the cases where zeroes can be inside the input. Also I have considered the cases of consecutive zeroes.
#include <stdio.h>
#include <string.h>
int main()
{
int n,i,ar[6010];
char str[6010];
unsigned long long int dp[6010];
while(1)
{
int flag=0;
scanf("%s",str);
if(str[0]=='0')
break;
for(i=0;str[i]!='\0';i++) //copy string to array
{
ar[i+1]=str[i]-'0';
}
n=i;
for(i=1;i<=n-1;i++) //checking for continous two zeroes
{
if(ar[i]==0&&ar[i+1]==0) flag=1;
if(ar[i]>2&&ar[i+1]==0)flag=1;
}
dp[1]=1;
if(ar[1]*10+ar[2]<=26&&ar[2]!=0)dp[2]=2;
else dp[2]=1;
if(ar[2]==0)dp[1]=0;
for(i=3;i<=n;i++)
{
if(ar[i]!=0)
{
dp[i]=dp[i-1];
if(ar[i-1]*10+ar[i]<=26)
{
dp[i]+=dp[i-2];
}
}
else
{
if(ar[i-2]*10+ar[i-1]<=26)
{
dp[i]=dp[i-2];
dp[i-1]=0;
}
else
{
dp[i]=dp[i-1];
dp[i-1]=0;
}
}
}
if(flag==0)
printf("%llu\n",dp[n]);
else
printf("0\n");
}
return 0;
}
There is some logical error in my code but I'm not able to figure out what it is. When I run my code it doesn't give me desired results.
OUTPUT:
Enter an infix expression
2+3
2
I get 2 as my postfix expression whereas I should be getting 23+.
Please see if anyone could help me out with this one.
#include<stdio.h>
#include<conio.h>
#include<stdlib.h>
#include<ctype.h>
#define max 20
int top=-1;
char infix[max],postfix[max],stack[max];
char pop();
int empty();
void push(char );
int precedence(char );
void infix_to_postfix(char * ,char * );
void main()
{
clrscr();
printf("Enter an infix expression\n");
gets(infix);
infix_to_postfix(infix,postfix);
printf("%s",postfix);
getch();
}
void infix_to_postfix(char infix[max],char postfix[max])
{
int i=0,j=0;
char value,x;
for(i=0;infix[i]!='\0';i++)
{
value=infix[i];
if(isalnum(value))
{
postfix[j]=value;
j++;
}
else
{
if(value=='(')
push('(');
else
{
if(value==')')
{
while((x=pop())!='(')
{
postfix[j]=x;
j++;
}
}
else
{
while(precedence(value)<=precedence(stack[top])&&!empty())
{
x=pop();
postfix[j]=x;
j++;
}
push(value);
}
}
}
}
while(!empty())
{
x=pop();
postfix[j]=x;
j++;
}
postfix[j]='\0';
}
void push(char x)
{
if(top==max-1)
printf("stack overflow\n");
else
{
top++;
stack[top]=x;
}
}
char pop()
{
char x;
x=stack[top];
top--;
return x;
}
int empty()
{
if(top==-1)
return(0);
return(1);
}
int precedence(char value)
{
if(value=='(')
return(0);
if(value=='+'||value=='-')
return(1);
if(value=='*'||value=='/'||value=='%')
return(2);
return(3);
}
Generally, the logic of your code is OK except a return value mistake in the empty() function.
In the empty(), it should return 1 while stack is empty.
int empty(){
if(top==-1)
return(0); <-- !!! here should return 1
}
Otherwise,
it will go into the while loop at while(precedence(value)<=precedence(stack[top])&&!empty()) even when stack is empty.
And then postfix[j] = x may write a redundant 0(now top= -2) to postfix array.
Finally,under the input 2+3, the postfix[] will be {'2','\0','3','+',...}, which result in the abnormal output 2.
So, it will work after modifying the empty() function, such as
int empty()
{
if(top==-1)
return(1); // not return(0)
return(0);
}
Output:
Enter an infix expression
2+3
23+
all you need to do is change your empty() function
you are checking for !empty() in if condition, but you are returning 0, when it is empty, this will make the condition true, i.e. Stack is not empty. Change the return value to 1 in case of empty stack.
Ok this has been driving me crazy. I solved a problem on spoj called MIXTURES (http://www.spoj.com/problems/MIXTURES/). I don't know why i keep getting segmentation fault. There is also one catch in the problem that there is no explicit indicator for end of input. I think I have handled it correctly but correct me if I am wrong. Here is my code
#include<stdio.h>
#include<stdlib.h>
typedef struct temp
{
int modSum; //the modular sum of the cluster
int smoke; //the minimum smoke that a cluster can give.
}clusterInfo;
int fxDP(int *A,int len)
{
int i,j,k,smoke1,smoke2;
clusterInfo **dpArr=(clusterInfo **)malloc(sizeof(clusterInfo *)*(len-1));
for(i=0;i<len-1;i++)
dpArr[i]=(clusterInfo *)malloc(sizeof(clusterInfo)*(len-i-1)); //len- ( (i+2) -1)= len-i-1
//dpArr[i] gives info of all clusters of length i+2
//base case for clusterLength=2
for(i=0;i<len-1;i++)
{
dpArr[0][i].modSum=(A[i]+A[i+1])%100;
dpArr[0][i].smoke=A[i]*A[i+1];
}
//endBase Case
//induction
for(i=1;i<len-1;i++) //lengthOfCluster=i+2
{
for(j=0;j<len-i-1;j++) //len-i-1+i+2-1=len
{
smoke1=(dpArr[i-1][j].modSum*A[j+(i+2)-1]) + dpArr[i-1][j].smoke;
smoke2=(A[j]*dpArr[i-1][j+1].modSum) + dpArr[i-1][j+1].smoke;
dpArr[i][j].smoke=smoke1<smoke2 ? smoke1:smoke2 ;
dpArr[i][j].modSum=(dpArr[i-1][j].modSum+A[j+(i+2)-1])%100;
}
}
int result=dpArr[len-2][0].smoke;
free(dpArr);
return result;
}
int main()
{
int *A; int len,i;
while(1)
{
scanf("%d",&len);
if(feof(stdin)) break;
A=(int *)malloc(sizeof(int)*len);
for(i=0;i<len;i++)
scanf("%d",&A[i]);
printf("%d\n",fxDP(A,len));
}
return 0;
}
int result=dpArr[len-2][0].smoke;
What happens if len=1 ??