User- Defined Function Returns 0 even when it should not

563 views c
0

Custom Input : 2 0 1 1 3 0 1 1 -1

Expected output : YES.

My Output : NO.

My Code :

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

int pv(int *a, int i){ //Function to create positional value.
if(a[i]!=0) return (a[i]+i);
else return 0;
}

int main() {
//code
int i,j,k,check=0;

int *a = (int *)malloc(1024*sizeof(int));
for(i=1;;i++) { scanf("%d",a+i);
if(*(a+i)==-1) { i--; break; } }
a = realloc(a,(i+1)*sizeof(int));//Just to decrease the size.

//Array of numbers inputed with designation from 1 formed.

int max_pv =0;

for(k=1;k<i;){


for(j=k+1;j<=pv(&a[k],k);){
    if(max_pv<pv(&a[j],j)) {
        max_pv = pv(&a[j],j);
        check =j;//Location of max_pv.
    }
}

k = check;
if(max_pv==0) { printf("NO"); return 0; }
if(max_pv>=i) { printf("YES"); return 0;}
max_pv = 0;
}
}

Problem Statement :

You will be given as input, a list of non-negative integers. The list will end with a -1 but the -1 is not a part of the list. The value of a number in this list denotes its "jump size".

For example, if the number at location i is 3, then the jump size at that element is 3. This means that all locations to the right of that location, within a distance of 3, are reachable from that location in a single jump. More precisely, in a single "jump" Mr C can go from location i to location i+1 or i+2 or i+3 if the number at location i is 3.

The first number of the list is said to be at location 1 (not like arrays where the first element is subscript 0). The number at location j will be said to be "reachable" from location i if it can be reached in any number of jump. Mr C starts by jumping on location 1 (this is his initial jump). He can now take any number of jumps, in any order, as allowed by the above rules. However, all jumps are made to the right of the list i.e. no backward jumps.

Print, as your output "YES" (without quotes) if the last location in the list (i.e. the location just before -1 is there) is reachable from location 1, else print "NO" (without quotes).

My problem :

I tried running the debugger on this code and the error I'm getting is that the function pv is returning zero even for k = 1.

In this example a[1] = 2. So the function should return a[1] + 2 = 3. But it's returning 0.

This is according to the debugger. If any other problem persists please mention them as well.

Thank you.

answered question

1 Answer

12

You are passing a pointer to a[j] (or a[k]) instead of just a to pv.

posted this

Have an answer?

JD

Please login first before posting an answer.