Answer:
- def nth(arr, length, match, n):
- count = 0
- for i in range(0, length):
- if(arr[i] == match):
- count += 1
-
- if(count == n):
- return i
-
- myArr = [2, 3, 4, 3, 5, 6, 7, 3, 5, 8, 9]
- print(nth(myArr, 10, 5, 2))
Step-by-step explanation:
The solution code is written in Python 3.
Firstly, create a function and name it as nth that takes four inputs, arr, length, match and n as required by the question (Line 1).
Next create a counter variable count (Line 2). This is used to track the current number of occurrence of the match in the list.
Create a for loop to iterate through each number in the array and if any element is equal to the match, increment the count by one (Line 3 - 5)
In the same loop, create another if statement to check if the current count number is equal to input n. If so return the current i index (Line 7-8).
At last, test the function using a sample list (Line 10) and print the return output. We shall get 8 because the nth occurrence of 5 is positioned in index-8 of the list (Line 11).