One day you awake only to find yourself caught in an array. You try to just walk out of there, taking one index at the time, but it seems there are other rules:
The array is completely filled with natural numbers.
- If you find yourself on an index
n
, you go to the indexarray[n]
, except: - If you find yourself on an index
n
which is a prime number, you takearray[n]
steps back
Example:
You start on index 4
, in this array (start index is 0):
array = [1,4,5,6,8,10,14,15,2,2,4,5,7];
-----------------^ you are here
As the value of the field you are on is 8
, you go to the index 8
as the first step. The field you land on contains the value 2
. You then go to index 2
as your second step. As2
is a prime number, you take 5 steps back, which is your third step. As there is no index -3
, you successfully escaped the array in a total of 3 steps.
Your task is:
To write a program or function, which accepts an array and a start index as parameter, and outputs the amount of steps to escape the array. If you can't escape the array (e.g. [2,0,2]
with start-index 2
=> you constantly go from index 2
to 0
), output a falsy value. You may use one-based indexing or zero-based indexing, but please specify which you use.
Test cases
Input: [2,5,6,8,1,2,3], 3
Output: 1
Input: [2, 0, 2], 2
Output: false
Input: [14,1,2,5,1,3,51,5,12,3,4,41,15,4,12,243,51,2,14,51,12,11], 5
;
Output: 6
The shortest answer wins.