Facing Wrong answer (everytime) -New to codechef community

/**solution for coin flip ***/
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

void GameResult(int I,long int N,int Q){

long int Hcount=0,Tcount=0;
char str = (char )malloc(N * sizeof(char));
if(I==1){
memset(str,‘H’, N
sizeof(char));
}else if(I==2){
memset(str,‘T’, N
sizeof(char));
}else{
printf(“wrong choice”);
exit(1);
}

for(int i=0;i<=N;i=i+2){
    
     if(N%2==0){
        str[i+1]='T';
    }else{
        str[i]='T';
    }

    
}

/counting for Q/

if(Q==1){
for(int i=0;i<N;i++){
if(str[i]==‘H’){
Hcount++;
}
}
printf(“%ld\n”,Hcount);
}else if(Q==2){
for(int i=0;i<N;i++){
if(str[i]==‘T’){
Tcount++;
}
}
printf(“%ld\n”,Tcount);
}
else{
printf(“Q-wrong choice”);
exit(2);
}

}
int main(void) {
// your code goes here

int Testcase=0;
int No_of_games=0;

scanf("%d",&Testcase);
/*I =1 initially all coins are Heads
  Q=1 have to count no of Head*/
 int I=0,Q=0;
 long int N=0;

for(int i=0;i<Testcase;i++){
    scanf("%d",&No_of_games);
    for(int j=0;j<No_of_games;j++){
        scanf("%d%ld%d",&I,&N,&Q);
        GameResult(I,N,Q);
    }
}

return 0;

}

Link: CodeChef: Practical coding for everyone

Please either format your code or (better!) link to your submission - the forum software has mangled it and it won’t compile! :slight_smile:

2 Likes

added link

1 Like

You’ve got some Undefined Behaviour here (out-of-bounds access):

for(int i=0;i<=N;i=i+2){

         if(N%2==0){
            str[i+1]='T';
        }else{
            str[i]='T';
        }
    }
3 Likes
for(int i=0;i<N;i=i+2){

         if(N%2==0){
            str[i+1]='T';
        }else{
            str[i]='T';
        }
    }
 I have tried this logic also as its still not working

That’s still an out-of-bounds access when N is even.

Edit:

Wait - or is it?

Edit2:

Ah, no - no out-of-bounds, there. But consider the test input:

1
1
2 6 1

@mohd_wamique1

2 Likes

thanks @ssjgz got the issue. :slight_smile:

1 Like