Cycle detection: Brent's The Tortoise and The Hare
Description:
For a general presentation of Cycle detection Problem see this kata: http://www.codewars.com/kata/5416f1834c24604c46000696
This kata follow: http://www.codewars.com/kata/cycle-detection-floyds-tortoise-and-the-hare
In Floyd Algorithm, tortoise and hare both move at one or two step at a time in the main part of the program wich can be a problem for big cycle as the tortoise and hare may visit the cycle multiple times before meeting. An important area of computer science where cycle appears is PRNG (Pseudo Random Number Generator). Big cycles are an important feature of PRNG for security. And even the simplest PRNG has a cycle lenght in millions. So we need to move faster. It will also be good to avoid too much evaluation of f as it may be a complicated function.
Brent's algorithm also require only two pointers, It is based on a different principle: searching for the smallest power of two that is larger than both and . For i = 0, 1, 2, etc., the algorithm compares the tortoise still at with each subsequent sequence value up to the next power of two visited by the hare while incrementing lambda, stopping when it finds a match. It has two advantages compared to Floyd's tortoise and hare algorithm: it finds the correct length of the cycle directly, rather than needing to search for it in a subsequent stage, and its steps involve only one evaluation of rather than three.
For finding , you can proceed simply: tortoise starting at ; hare starting at , move them forward at the same pace untill they agree.
Your goal is to code a function that will take a function and a starting point as input and return an array [mu, lambda]. Every function passed as argument will be periodic after some point.
Similar Kata:
Stats:
Created | Sep 15, 2014 |
Warriors Trained | 399 |
Total Skips | 167 |
Total Code Submissions | 238 |
Total Times Completed | 47 |
Python Completions | 31 |
JavaScript Completions | 20 |
Total Stars | 9 |
% of votes with a positive feedback rating | 76% of 19 |
Total "Very Satisfied" Votes | 13 |
Total "Somewhat Satisfied" Votes | 3 |
Total "Not Satisfied" Votes | 3 |
Total Rank Assessments | 21 |
Average Assessed Rank | 5 kyu |
Highest Assessed Rank | 3 kyu |
Lowest Assessed Rank | 8 kyu |