Detecting Cycles

CodeEval


行内の繰り返しを見つける。

設問

Given a sequence, write a program to detect cycles within it.
Input sample:

A file containing a sequence of numbers (space delimited). The file can have multiple such lines. e.g

2 0 6 3 1 6 3 1 6 3 1

Ensure to account for numbers that have more than one digit eg. 12. If there is no sequence, ignore that line.
Output sample:
Print to stdout the first sequence you find in each line. Ensure that there are no trailing empty spaces on each line you print. e.g.

6 3 1

やってみた

文字列の後ろから繰り返しがないかをチェック。
繰り返し文字列の長さは、2文字以上、全体の半分以下。

#!/usr/bin/env ruby

def detect_cycle(stack)
  (2..stack.size/2).each do |i|
    assume_cycle = stack[-i, i]
    next_cycle   = stack[-i*2, i]
    return assume_cycle.join(" ")  if assume_cycle == next_cycle
  end
  ''
end

ARGF.lines do |line|
  puts detect_cycle(line.split(/\s/))
end

あまりきれいじゃないなー。