Skip to content

Instantly share code, notes, and snippets.

@kenmazaika
Created September 7, 2015 16:46
Show Gist options
  • Save kenmazaika/11cadc6b05e132827027 to your computer and use it in GitHub Desktop.
Save kenmazaika/11cadc6b05e132827027 to your computer and use it in GitHub Desktop.

Floyd's Cycle Detection Algorithm

A quick blur why this matters, what the problem solves and how it works.

How to Run

Unit tests

To run the unit tests execute the following command

whatever

How to run the sample code

To run the sample code execute the following command

whatever
class LinkedListNode
attr_accessor :value, :next_node
def initialize(value, next_node=nil)
@value = value
@next_node = next_node
end
end
require_relative 'linked_list_node'
require_relative 'tortoise_hare'
node1 = LinkedListNode.new(37)
node2 = LinkedListNode.new(99, node1)
node3 = LinkedListNode.new(12, node2)
TortoiseHare.new(node3).traverse_nodes
node1.next_node = node3
TortoiseHare.new(node3).traverse_nodes
class TortoiseHare
attr_accessor :start, :fast, :slow
def initialize(start)
@start = start
@fast = fast = start
@slow = slow = start
end
def traverse_nodes
return false if fast.next_node.nil?
moves
end
def moves
if @fast.next_node != nil && @fast.next_node.next_node !=nil
@fast = @fast.next_node.next_node
@slow = @slow.next_node
nodes_equal
end
end
def nodes_equal
@fast == @slow ? (return true) : (traverse_nodes)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment