Last active
May 1, 2017 16:18
-
-
Save nononoy/1e96de72989d38338d9ef8a7b91afabd to your computer and use it in GitHub Desktop.
Numeric extension to get Look-and-say sequence number implementation. Ruby > 2.4.0
This file contains hidden or 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
module SpecificNumeric | |
refine Numeric do | |
PRESET_ITERATIONS_COUNT = 5 | |
def look_and_say | |
_deep_look_and_say(Array.new(1, self)) | |
end | |
private | |
def _deep_look_and_say(arr, iteration_num = 0) | |
if iteration_num < PRESET_ITERATIONS_COUNT | |
arr << say_it!(arr.last) | |
arr = _deep_look_and_say(arr, iteration_num + 1) | |
end | |
arr | |
end | |
def say_it!(number) | |
pronounced = '' | |
lr_digits = number.digits.reverse | |
lr_digits.each_with_index do |digit, index| | |
next if index > 0 && lr_digits[index - 1] == digit | |
counter = check_next_digit(lr_digits, digit, index) | |
pronounced += "#{counter}#{digit}" | |
end | |
pronounced.to_i | |
end | |
def check_next_digit(digits, current_digit, index, counter = 1) | |
counter = check_next_digit(digits, digits[index + 1], index + 1, counter + 1) if current_digit == digits[index + 1] | |
counter | |
end | |
end | |
end |
This file contains hidden or 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
require_relative "look_and_say" | |
require "test/unit" | |
class TestSpecificModule < Test::Unit::TestCase | |
def test_main | |
assert_equal([1, 11, 21, 1211, 111221], 1.look_and_say.each.take(5)) | |
assert_equal([10, 1110, 3110], 10.look_and_say.each.take(3)) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment