Help me debug this code

My code:
include <stdio.h>

int main(void) {
// your code goes here
int t,num[1000000000],i,n,x,d,cont;
scanf(“%d”,&t);
while(t–)
{ cont=0;
d=0;
for(i=0;i<1000000000;i++)
{
num[i]=0;
}
scanf(“%d%d”,&n,&x);
for(int j=0;j<n;j++)
{
scanf(“%d”,&d);
num[d]=1;
}
for(i=0;i<1000000000;i++)
{
if(num[i]==1)
cont=cont+1;
}
if((n-cont)<x)
printf(“%d\n”,n-x);
else
printf(“%d\n”,cont);
}
}

Lang:C
Problem link:Chocolate Monger Practice Problem in Level up from 1* to 2* - CodeChef

This is a commented version of your code.
I made some changes.

#include <stdio.h>
#include <stdlib.h>

int compare (const void * a, const void * b) {
   return *(int*)a -*(int*)b;
}

int main(void) {
    // your code goes here
    int t,i,n,x,d,cont;
    //int num[1000000000];
    
    scanf("%d",&t);
    while(t--){
        cont=0;
        d=0;
        /*
            I understad your static array of 10^9 can be "faster"
            because it sends memory allocation time to compilation time,
            but don't do it unless it extremelly needed.
            It's not needed here.
        */
        
        
        // Logic starts here
        scanf("%d %d",&n,&x);
        
        // Wrong handling of inputs.
        // This is how it should be
        // You should save the numbers as they are
        
        int num[n];
        for(int j=0; j<n; j++){
            scanf("%d",&num[j]);
        }
        
        /*
            This does not solve the problem.
            It asks you to know how many different candies
            the girl can eat.
            "cont" will always be equal to n
            
            for(i=0;i<1000000000;i++){
                if(num[i]==1)
                cont=cont+1;
            }
            if((n-cont)<x)
                printf("%d\n",n-x);
            else
                printf("%d\n",cont);
        */
        
        /* -------------------------------------------------------
            First, determinate the number of different candies.
            An approach can be sorting the numbers,
            and then counting the differences.
            "qsort" needs an auxiliary function I named "compare".
            "compare" is defined above.
        */ 
        qsort(num, n, sizeof(int), compare);
        
        cont = 1;
        for(int j=1; j<n; j++){
            if (num[j-1] != num[j]){
                cont++;
            }
        }
        
        /*
            Knowing the different candies and the candies
            Sabrina can eat, then the max amont she can eat
            is the min between the different available and hers
        */
        
        if (cont < n-x){
            printf("%d\n",cont);
        }
        else{
            printf("%d\n", n-x);
        }
    }
    
    return 0;
}

Thanks a lot. I really didn’t know how to use qsort. This is really helpful.

1 Like