Algorithm not getting into if condition (Sherlock and the Valid String) - c

I am basically trying to solve this challenge. This is my code:
int arr[26]={0};
int freq=0;
int deletion=0;
for(int i=0;i!='\0';i++)
{
arr[s[i]-'a']++;
}
freq=arr[0];
for(int i=1;i<26;i++)
{
if(freq!=arr[i])
{
deletion++;
return "HAHA";
}
}
if(deletion>1)
{
return "NO";
}
else
{
return "YES";
}
I realized it wasn't getting into the deletion++, and then I used a return "HAHA" to make sure of it.
For some reason, the condition freq!=arr[i] never gets satisfied, even when the content of the freq and arr[i] are different. I guess I am getting trapped in a very silly mistake here.

This line has a problem:
for(int i=0;i!='\0';i++)
\0 is actually a null-terminator. Probably you meant this:
for(int i = 0; i != size_of_array_s; i++)
OR:
for(int i = 0; s[i] != '\0'; i++)

this line is a problem in line
for(int i=0;i!='\0';i++)

Related

Check for palindrome using stack in C

I'm new to C, and I've been given a question to write a program to check palindrome words.
I did the following code, it gives an output. but the output is always "No". The idea of what I did in this code is, I first divided the string and pushed them into one stack (stacka). then pushed the rest of the letters to another stack(stackb). Then I pop both of those stacks and check whether the letter returning from each pop function(of stacka and stackb) is equal or not. if not it will return 0.
below is the code.
Thank you in advance. Have a nice day!.
#include <stdio.h>
#include <string.h>
char stacka[5];
char stackb[5];
int topa = -1;
int topb = -1;
void pusha(char e) {
topa++;
stacka[topa] = e;
}
void pushb(char e) {
topb++;
stackb[topb] = e;
}
char popa() {
char e = stacka[topa];
topa--;
return e;
}
char popb() {
char e = stackb[topb];
topb--;
return e;
}
int palindrome(char str[]) {
int i, length = strlen(str);
int mid = length / 2;
for (i = 0; i < mid; i++) {
pusha(str[i]);
}
if (length % 2 != 0) {
i++;
}
for (i = length - 1; i >= mid; i--) {
pushb(str[i]);
}
int f;
for (f = mid; f >= 0; f--) {
char ele1 = popa();
char ele2 = popb();
if (ele1 != ele2)
return 0;
}
return 1;
}
int main() {
char str[] = "madam";
if (palindrome(str)) {
printf("Yes");
} else
printf("No");
}
At a first glance, I have found the following issues in your code.
if(length % 2 !=0)
{
i++;
}
for(i=length-1;i>=mid;i--)
{
pushb(str[i]);
}
Your if block does not make any impact on the code and it is unnecessary as well. for loop has an issue as well which can cause your problem.
Let me elaborate a bit. Let's say your input is "madam" and according to your solution, first for loop is doing ok.
int mid=length/2;
for(i=0;i<mid;i++)
{
pusha(str[i]);
}
As your input is "madam" your value for mid would be 2. so, the first stack will contain the letter, 'm', 'a'. This is alright up to this.
In the second for loop there is a issue,
for(i=length-1;i>=mid;i--)
{
pushb(str[i]);
}
According to this stack will contain 'm', 'a', 'd'.
Now I would say the correction here according to me. First of all, you remove the first if block, then do this modification on the second for loop.
for(i=length-1;i>mid;i--)
{
pushb(str[i]);
}
Then finally in last for loop,
for(f=mid-1;f>=0;f--)
{
char ele1=popa();
char ele2=popb();
if(ele1!=ele2)
return 0;
}
I have not compiled and run the code with my given corrections. But I think this will help you to figure out the issues with your code.
First u change the condition of for loop in palindrome function.
for(i=length-1;i>mid;i--)
{
pushb(str[i]);
}
தலைவா எனக்கு ஆங்கிலம் நல்லா வராது.
First u change the condition of for loop in palindrome function.
for(i=length-1;i>mid;i--)
{
pushb(str[i]);
}
Your program is correct.

Having trouble with forever loop

#include <stdio.h>
int main(){
int n,copy,counter=0,prevcounter,prev;
scanf("%d",&n);
while(n>0){
counter = 0;
n--;
copy = n;
while(copy>0){
--copy;
if(n%copy==0){
counter++;}
if(copy==0)break;
}
if(counter>prevcounter){
prevcounter = counter;
prev = n;
}
}
printf("%d",prev);
}
So here is my code:The problem is that this code goes to forever loop and the problem is right here
while(copy>0)
but if i change it to
while(copy>1)
It is working....I am trying to get why it is going to forever loop but i cant find the answer..I am decremending copy and when it gets 0 it should break from the loop..I even added another check
if(copy==0)break;
but still it didnt work..Any sugestions?Thanks
You are using % when copy=0 also. It is a bug leading to undefined behavior.(Divide by zero).
prevcounter is uninitialized.
Code will be something like this:-
#include <stdio.h>
int main(){
int n,copy,counter=0,prevcounter=0,prev;
scanf("%d",&n);
while(n>0)
{
counter = 0;
n--;
copy = n;
while(copy>0)
{
--copy;
if(copy && n%copy==0){
counter++;
}
}
if(counter>prevcounter){
prevcounter = counter;
prev = n;
}
}
printf("%d",prev);
}
You needed to consider all the values of the copy that may come up during execution. Here in the loop you will exclude the cases when copy becomes zero and if(copy && n%copy==0) ensures that.

Reading correctly from a 2D char array in a function

I can´t read from the char array
This is how I pass the string into my array for each test case and that works fine but passing the array is a problem. I looked it up here: Passing arrays and matrices to functions as pointers and pointers to pointers in C
I still get the warning that I compare between a pointer and an integer.
char klammern[MAX][STRING];
int i, test;
int ergebnis;
printf(" Test cases?:");
scanf("%d",&test);
getchar(); //catch Enter
for(i=0;i<test;i++)
{
fgets(klammern[i],30,stdin);
}
Here is how I pass the argument:
for(i=0;i<test;i++)
{
ergebnis = matching_brackets( klammern );
printf("%d ",ergebnis);
}
My function should count the numbers of brackets and return 1 if not all brackets are closed and 0 if everything is correct.
int matching_brackets(char (*klammern)[STRING])
{
int ergebnis, i;
int runde_klammern = 0;
for(i=0; *klammern[i] != '\n';i++)
{
if( *klammern[i] == '(')
{
runde_klammern++;
}
else if( *klammern[i] == ')')
{
runde_klammern--;
}
ergebnis = runde_klammern;
if ( ergebnis != 0)
{
return 1;
}
else
{
return 0 ;
}
While testing I saw that my for loop in the function read my array like this:
array [1][0]
array [2][0]
...
I want to loop the array like:
array[0][0]
array[0][1]
...
Edit: I do not get the compiler warning anymore after I fixed a typo in my function.
You have two problems, one is that your loop is wrong and the other is an operator precedence problem.
You should loop like e.g.
for (size_t i = 0; i < test; ++i)
{
for (size_t j = 0; klamern[i][j] != '\n'; ++j)
{
// Here `klamern[i][j]` is the current character
}
}
Note that you need to pass the test variable to the function as well.
The above loops also removes the second problem. (that *klamern[i] is seen by the compiler as *(klamern[i]) and not (*klamern)[i]).

What does a return statement within a loop do?

In the code below, str_replace_all replaces all occurrences of oldc with newc. str_replace_first is only supposed to replace the first occurrence of oldc with newc.
So str_replace_all loops through and it replaces all occurrences of oldc with newc, easy enough to understand. In the second function str_replace_first the code is identical, except for return 1 after finding and replacing the char. I don't exactly understand what return 1 does in this case. From what I am understanding it "breaks" the loop? I was hoping somebody could give me an explanation on how it replaces only the first occurrence.
size_t str_replace_all(char s[], int oldc, int newc)
{
size_t i;
size_t count = 0;
for (i=0; s[i]!='\0'; i++)
{
if (s[i] == (char)oldc)
{
s[i] = (char)newc;
count++;
}
}
return count;
}
int str_replace_first(char s[], int oldc, int newc)
{
size_t i;
for (i=0; s[i]!='\0'; i++)
{
if (s[i] == (char)oldc)
{
s[i] = (char)newc;
return 1; /* What exactly does this do? */
}
}
return 0;
}
return 1 escapes the function and returns a 1 to whatever has called it. return effectively escapes any function when it is called, this can be used in many applications to exit a function before it is 'complete'.
In this case:
int str_replace_first(char s[], int oldc, int newc)
{
size_t i;
for (i=0; s[i]!='\0'; i++)
{
if (s[i] == (char)oldc)
{
s[i] = (char)newc;
return 1; /* What exactly does this do? */
}
}
return 0;
}
The loop continues until it finds a character that matches oldc then replaces it with newc, then exits immediately before continuing on again. So as soon as it finds a match it will replace it then exit.
Here in str_replace_first when
s[i] == (char)oldc
condition becomes true in the loop, then then that character(old character) is replaced by the new one. and then return 1 returns the control to the calling function with a value of 1.(i.e neither the loop nor the function continues further).
1 was returned to mark that only 1 character was replaced.

Stop for loop upon returning value [closed]

Closed. This question does not meet Stack Overflow guidelines. It is not currently accepting answers.
Questions asking for code must demonstrate a minimal understanding of the problem being solved. Include attempted solutions, why they didn't work, and the expected results. See also: Stack Overflow question checklist
Closed 9 years ago.
Improve this question
This is the relevant function:
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] == 'a') {
return(1);
} else {
matrix[y][x] = 'b';
return(0);
}
}
}
}
And this is the relevant main() code:
char matrix[3][3];
int duplicate1 = 0;
do {
duplicate1 = computerChoice();
} while(duplicate1 == 1);
I'm attempting to scan through a 3x3 two dimensional array and check sequentially if each one is equal to "a". If so I want the function to return a "1" and continue checking. Once it finds an entry that is not equal to "a" it should set that entry equal to b, return 0 and stop looping.
I get some really weird results. If [1][1] has an "a" in it, the function doesn't do anything but just "freezes". If [2][2] has an "a" in it, the function correctly places a "b" in the entry [1][1].
This also happens if other entries are already filled.
Any thoughts?
your implementation seems buggy the code should continue till it is finding 'a' in each cell.If it doesn't find 'a' it should set it to 'b' and return 0. the loop will stop automatically when you return.
If both the loop completes that means every cell in matrix contains 'a'. and you should return 1;
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] == 'a') {
continue;
}
else {
matrix[y][x] = 'b';
return(0);
}
}
}
return 1;
}
I'm assuming what you mean is "I want to process the entire array, and return 1 if I ever found an a, and 0 otherwise". That can be achieved like so:
int found = 0;
for (size_t i = 0; i != 3; ++i)
{
for (size_t j = 0; j != 3; ++j)
{
if (matrix[i][j] == 'a') { found = 1; }
else { matrix[i][j] = 'b'; }
}
}
return found;
(By changing to ++found, you can also return the number of occurrences of 'a'.)
If on the other hand you want to return 0 as soon as you know there's a non-'a' in your data, it's simpler:
for (size_t i = 0; i != 3; ++i)
for (size_t j = 0; j != 3; ++j)
if (matrix[i][j] != 'a') { matrix[i][j] = 'b'; return 0; }
return 1;
I don't exactly understand what you mean by "return 1 and continue checking". I will assume that you want to scan the whole array, and return 1 if every position is an a; otherwise, return 0 and set the first position that was not an a to b. Here's the code:
int computerChoice() {
int x, y;
for (y=0;y<=2;y++) {
for (x=0;x<=2;x++) {
if (matrix[y][x] != 'a') {
matrix[y][x] = 'b';
return 0;
}
}
}
return 1;
}

Resources