6 kyu

Cycle Detection: greedy algorithm

419 of 622user3482173

Description:

In computer science, cycle detection is the algorithmic problem of finding a cycle in a sequence of iterated function values.

For any function ff, and any initial value x0x_0 in S, the sequence of iterated function values

x0,x1=f(x0),,xi=f(xi1),x_0, x_1 = f(x_0), \dots ,x_i = f(x_{i-1}), \dots

may eventually use the same value twice under some assumptions: S finite, f periodic ... etc. So there will be some iji \neq j such that xi=xjx_i = x_j. Once this happens, the sequence must continue by repeating the cycle of values from xix_i to xj1x_{j−1}. Cycle detection is the problem of finding ii and jj, given ƒƒ and x0x_0. Let μ\mu be the smallest index such that the value associated will reappears and λ\lambda the smallest value such that xμ=xλ+μx_{\mu} = x_{\lambda + \mu}, λ\lambda 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. μ\mu is 2 (first 6) λ\lambda 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 [μ\mu,λ\lambda] 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

Mathematics
Algorithms

Stats:

CreatedSep 15, 2014
PublishedSep 16, 2014
Warriors Trained1787
Total Skips438
Total Code Submissions3301
Total Times Completed622
Python Completions419
JavaScript Completions173
Ruby Completions57
Total Stars61
% of votes with a positive feedback rating91% of 106
Total "Very Satisfied" Votes91
Total "Somewhat Satisfied" Votes11
Total "Not Satisfied" Votes4
Total Rank Assessments8
Average Assessed Rank
6 kyu
Highest Assessed Rank
6 kyu
Lowest Assessed Rank
7 kyu
Ad
Contributors
  • user3482173 Avatar
  • jhoffner Avatar
  • GiacomoSorbi Avatar
  • bidouille Avatar
  • utoppia Avatar
Ad