Last active
March 31, 2016 07:10
-
-
Save gabyshev/1ff061892673f24450f1d0d619a95cbf to your computer and use it in GitHub Desktop.
Look and say sequence implementation
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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