Skip to content

Instantly share code, notes, and snippets.

@mqu
Last active December 15, 2015 14:19
Show Gist options
  • Save mqu/5273462 to your computer and use it in GitHub Desktop.
Save mqu/5273462 to your computer and use it in GitHub Desktop.
codingame : Conway series ; this script fails to few tests but should be OK and very quick. All the job is done with regular expression that do "group by", and perform string length. This algorithm is called "lookandsay" and is visible somewhere. keywords : codingame, ruby, conway sequence, look'say, look-and-say
def conway(start, count)
str=start
(count-1).times do
str = str.gsub(/(.)\1*/) {$&.length.to_s + $1}
end
return str.split('').join(' ')
end
# read data from STDIN or from FILES passed as args and split as lines
lines=ARGF.read.split("\n")
puts conway(lines[0], lines[1].to_i)
# this one is OK for numbers greater > 9
def conway(start, _count)
seq = [start]
_seq = []
(_count-1).times do
current=seq[0]
count=0
seq.each_with_index do |v, i|
if seq[i]!=current
_seq << count
_seq << current
current=seq[i]
count=1
else
count+=1
end
end
_seq << count
_seq << current
seq = _seq.clone
_seq = []
end
return seq.join(" ")
end
# read data from STDIN or from FILES passed as args and split as lines
lines=ARGF.read.split("\n")
puts conway(lines[0].to_i, lines[1].to_i)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment