Cycle Detection: greedy algorithm
Description:
In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values.
For any function , and any initial value in S, the sequence of iterated function values
may eventually use the same value twice under some assumptions: S finite, f periodic ... etc. So there will be some such that . Once this happens, the sequence must continue by repeating the cycle of values from to . Cycle detection is the problem of finding and , given and . Let be the smallest index such that the value associated will reappears and the smallest value such that , is the loop length.
Example:
Consider the sequence:
2, 0, 6, 3, 1, 6, 3, 1, 6, 3, 1, ....
The cycle in this value sequence is 6, 3, 1. is 2 (first 6) is 3 (length of the sequence or difference between position of consecutive 6).
The goal of this kata is to build a function that will return [,] when given a short sequence. Simple loops will be sufficient. The sequence will be given in the form of an array. All array will be valid sequence associated with deterministic function. It means that the sequence will repeat itself when a value is reached a second time. (So you treat two cases: non repeating [1,2,3,4] and repeating [1,2,1,2], no hybrid cases like [1,2,1,4]). If there is no repetition you should return [].
This kata is followed by two other cycle detection algorithms: Loyd's: http://www.codewars.com/kata/cycle-detection-floyds-tortoise-and-the-hare Bret's: http://www.codewars.com/kata/cycle-detection-brents-tortoise-and-hare
Similar Kata:
Stats:
Created | Sep 15, 2014 |
Published | Sep 16, 2014 |
Warriors Trained | 1787 |
Total Skips | 438 |
Total Code Submissions | 3301 |
Total Times Completed | 622 |
Python Completions | 419 |
JavaScript Completions | 173 |
Ruby Completions | 57 |
Total Stars | 61 |
% of votes with a positive feedback rating | 91% of 106 |
Total "Very Satisfied" Votes | 91 |
Total "Somewhat Satisfied" Votes | 11 |
Total "Not Satisfied" Votes | 4 |
Total Rank Assessments | 8 |
Average Assessed Rank | 6 kyu |
Highest Assessed Rank | 6 kyu |
Lowest Assessed Rank | 7 kyu |