Skip to content

Instantly share code, notes, and snippets.

@gabyshev
Last active March 31, 2016 07:10
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save gabyshev/1ff061892673f24450f1d0d619a95cbf to your computer and use it in GitHub Desktop.
Save gabyshev/1ff061892673f24450f1d0d619a95cbf to your computer and use it in GitHub Desktop.
Look and say sequence implementation
def look_and_say(rows: 6)
# set first row manually
row = '1'
rows.times do
puts row
# split row to array to be able to count elements
row_chars = row.chars
# emptying string to inject count results
row = ''
# offset to which element to look at from current
offset = 1
row_chars.each_with_index do |item, index|
# skip if previous element is equal to current because it should have been counted
next if index > 0 && item == row_chars[index - 1]
# by default count = 1 because element itself is consist only himself
count = 1
# increment count and offset if next element is equal to current
while item == row_chars[index + offset] && row_chars.size > index + offset
count += 1
offset += 1
end
# next iteration start from looking at next element
offset = 1
# inject result of counting current item amount to row
row << "#{count}#{item}"
end
end
end
look_and_say
# 1
# 11
# 21
# 1211
# 111221
# 312211
look_and_say(rows: 8)
# 1
# 11
# 21
# 1211
# 111221
# 312211
# 13112221
# 1113213211
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment