Problem 45498. Trace the path of a harmful chemical in an ecological network
An ecological network consists of the cycles of nature, such as the water cycle, the carbon cycle, the oxygen cycle, etc. Due to human activities, harmful chemicals (or persistent pollutants) are now entering these cycles and may stay there forever. Your job is to track a specific unknown chemical inside an ecological network.
For this problem, a network involves N sites in nature, labelled as Site 1, Site 2, ..., Site N. Researchers have identified an ecological network for you, which is given as a [1 x N] row vector called P. The network is read as follows: "A chemical that enters Site i always end up at Site P(i)". Consider the following example:
If a chemical enters Site: 1 2 3 4 5 it will end up at Site: P = [3 1 5 2 4]
If a harmful chemical enters the ecological network from Site 2, it will be traced to Site 1 (which is P(2)), then eventually at Site 3, then at Site 5, then at Site 4, then back to Site 2. Hence, the path of this chemical is [2 1 3 5 4].
Write a function that takes a vector P and a starting site S. Output the path of the chemical after it enters Site S in the given ecological network. You are ensured that:
- P is always a permutation of integers 1 to N.
- 2 <= N <= 100
- 1 <= S <= N
See sample test cases:
>> trace_chemical([3 1 5 2 4],2) ans = 2 1 3 5 4 >> trace_chemical([3 1 5 2 4],1) ans = 1 3 5 4 2 >> trace_chemical([4 1 6 5 2 3],1) ans = 1 4 5 2
Solution Stats
Problem Comments
Solution Comments
Show commentsProblem Recent Solvers28
Suggested Problems
-
3823 Solvers
-
1882 Solvers
-
Project Euler: Problem 3, Largest prime factor
1415 Solvers
-
Flip the main diagonal of a matrix
794 Solvers
-
436 Solvers
More from this Author19
Problem Tags
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!