Draft

Cycle detection: Brent's The Tortoise and The Hare

31 of 47user3482173

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 2i 2^i that is larger than both λ \lambda and μ \mu . For i = 0, 1, 2, etc., the algorithm compares the tortoise still at x2i1 x_{2^{i-1}} 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 λ \lambda of the cycle directly, rather than needing to search for it in a subsequent stage, and its steps involve only one evaluation of f f rather than three.

For finding μ \mu , you can proceed simply: tortoise starting at x0 x_0 ; hare starting at xλx_\lambda, 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.

Mathematics
Algorithms

Stats:

CreatedSep 15, 2014
Warriors Trained399
Total Skips167
Total Code Submissions238
Total Times Completed47
Python Completions31
JavaScript Completions20
Total Stars9
% of votes with a positive feedback rating76% of 19
Total "Very Satisfied" Votes13
Total "Somewhat Satisfied" Votes3
Total "Not Satisfied" Votes3
Total Rank Assessments21
Average Assessed Rank
5 kyu
Highest Assessed Rank
3 kyu
Lowest Assessed Rank
8 kyu
Ad
Contributors
  • user3482173 Avatar
  • kazk Avatar
  • utoppia Avatar
Ad