Home > Software engineering >  hopscotch game in python
hopscotch game in python

Time:11-09

I am trying to solve this question for 2 days but unable to solve it, gets really frustrated. I hope anyone can help me to get rid out of this problem.

Write a program for given an integer list where each number represents the number of hops you can make in hopscotch game, determine whether you can reach to the last index starting at index 0.

For example, [2, 0, 1, 0] returns True while [1, 1, 0, 1] returns False.

Input Format

single line space separated integers

Constraints

len(list) > 0

Output Format

Boolean True or False

Sample Input 0

2 3 1 1 4

Sample Output 0

True

Explanation 0

Input: nums = [2,3,1,1,4] Output: True Explanation: Jump 1 step from index 0 to 1, then 3 steps to the last index. Sample Input 1

3 2 1 0 4

Sample Output 1

False

Explanation 1

Input: nums = [3,2,1,0,4] Output: False Explanation: You will always arrive at index 3 no matter what. Its maximum jump length is 0, which makes it impossible to reach the last index.

CodePudding user response:

Assuming I understood the question correctly, this should be the solution:

sample1 = [2,3,1,1,4]
sample2 = [3,2,1,0,4]

def hopscotch(sample):
    last_index = len(sample) - 1
    current_index = 0
    while True:
        if current_index == last_index:
            return True
        elif current_index > last_index:
            return False #Or True depending on if you can hop off the end
        elif sample[current_index] == 0:
            return False
        else:
            current_index  = sample[current_index]  

Just increase the index by the value at that index and check if you are at the end of the list, over the end of the list or the current element is 0.

CodePudding user response:

You can find optimum solutions at Solutions section in Leetcode: https://leetcode.com/problems/jump-game/solutions/

  • Related