Let's jump

Assume an array of numbers [ 4 , 2 , 5 , 1 , 0 , 3 , 7 , 8 , 6 , 9 ] [4, 2, 5, 1, 0, 3, 7, 8, 6, 9] . Initially you are standing on the very first number, say '4'. Now jump 4 steps forward (till number '0'). Now you are standing on ZERO hence just step to the next number '3' (doing this is NOT a jump) then jump 3 steps again, you've reached number '6', finally you'll jump 6 steps forward to be out of the array. Collectively, you needed to jump thrice.

How many times do you need to jump in this case?

Details and Assumptions:

  • Treat all ZEROS as ONES and do NOT consider it a jump.
1995 2016 2015 1997

This section requires Javascript.
You are seeing this because something didn't load right. We suggest you, (a) try refreshing the page, (b) enabling javascript if it is disabled on your browser and, finally, (c) loading the non-javascript version of this page . We're sorry about the hassle.

2 solutions

David Holcer
Jan 13, 2016
 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
fname="array.txt"
text_file = open(fname, "r")
lines = text_file.read().split(',')

jumps=0
n=0
while n<len(lines):
    if (lines[n]!='0'):
        jumps+=1
        n+=int(lines[n])
    else:
        n+=1
print jumps              

Interesting question. The size of the array required using an external file to speed up program speed. My method simply checked if each position with value x in the array was not 0, and jumped to the space x in front (in the array). If the value was zero, it would jump to the next value, but not count it as a jump.

Zeeshan Ali
Jan 11, 2016

Following is an algorithm (a general method) to do the task:

1
2
3
4
5
6
7
8
    jumps=0
    for i=0 to Arr.length-1
        if Arr[i] is not 0
            i=i+Arr[i]
            jumps=jumps+1
        else
            i=i+1
    return jumps

I hope that it would help you understand the concepts of Array Traversing and Manipulating.

0 pending reports

×

Problem Loading...

Note Loading...

Set Loading...