Yes, this is very similar to this question. However, that concerns infinite linked lists, and you do not need to handle out of bounds indexes in that question.
You are in a strange city, looking for the fabled Nineteenth Bakery, where it is said they sell the most delicious deleted posts. The order of shops here is strange. Each street has a number of shops on it, but they are not numbered in order. Instead, each shop has a number n
, indicating that the next shop is n
shops form the beginning of the street.
For example, consider the street s
, which is like this: [1,4,3,-1,2]
.
To find shop number 3, you first start with the first shop on the street, shop #1. In this case, s[0]
is 1
. That means that shop #2 is at index 1
. s[1]
is 4
, meaning shop #3 is at index 4. If an index is -1
or is greater than the bounds of the array, that means that there is no "next" shop. A shop may reference a shop already visited. For example, if you are at shop #10 and the next shop has been visited and is #5, that means shop #5 is also shop #11.
The Task
You are given a positive number n
and a street, which is a non-empty list of numbers. n
may be 1 or 0-indexed. You are to follow the path of shops until you get to shop #n
. Then output the index (0, or 1-indexed) of shop #n
in the list. If there is no shop #n
, output any consistent value that is not a positive integer (i.e negative integers, null
, undefined
, etc.).
Examples (Array indexes 0-indexed, n
1-indexed)
2, [3,-1, 8, 2] -> 3
1, [13, 46] -> 0
4, [1,2,3,4] -> 3
5280, [8] -> -1
3, [2,0,2,-1] -> 2
Scoring
This is code-golf, so the shortest answer in bytes wins.
-1
? (They are out of bounds but then again, so is-1
.) \$\endgroup\$n
and the array.... \$\endgroup\$