简体   繁体   中英

Jumping on the Cloud in C Hacker Rank

I have written a solution for a HackerRank question jumping on clouds in C language. The question is:

There is a new mobile game that starts with consecutively numbered clouds. Some of the clouds are thunderheads and others are cumulus. The player can jump on any cumulus cloud having a number that is equal to the number of the current cloud plus or. The player must avoid the thunderheads. Determine the minimum number of jumps it will take to jump from the starting position to the last cloud. It is always possible to win the game.

For each game, you will get an array of clouds numbered if they are safe or if they must be avoided.

Some of the test cases are passing for my code but most are failing. Sometimes, it's returning count + 1 , sometimes count - 1 . I cannot find where is it failing?

#include<stdio.h>
int main()
{
    int n;
    scanf("%d",&n);
    int c[n];
    scanf("%d",&c[n]);
    int count = 0;
    for(int i=0; i<n;)
    {
        if(c[i+2]== 0 || i+2 <= n)
        {
            i=i+2;
            count++;
            printf("%d",count);
        }
        
        else
        {
            i++;
            count++;
            
        }
        
    }
    printf("%d\n",count-1);
    return 0;

}

The line, if(c[i+2]== 0 || i+2 <= n) exhibits undefined behaviour, because you are potentially attempting to access an array element that is out-of-bounds.

You need to check the value of i before any attempt at reading the array element:

if ((i+2 < n) && (c[i+2]== 0)) // Extra brackets added for clarity: not actually needed
    ...

Note the last element of an array of size n will be at index n-1 (arrays are zero-based in C). Placing the test of the value of i+2 first will prevent the second test being executed through so-called short-circuiting .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM