Last active
April 23, 2021 16:55
-
-
Save hugohernani/756b14e6e52b0788403c012ef0fce7ca to your computer and use it in GitHub Desktop.
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
class NumberFormatter | |
def format(_number) | |
raise NotImplementedError, "subclass should specify its formatting details" | |
end | |
end | |
class NonPositiveFormatter < NumberFormatter | |
def format(_number) | |
"\n" # nothing to print | |
end | |
end | |
class PositiveFormatter < NumberFormatter | |
def format(number) | |
"#{number}\n" | |
end | |
end | |
class SmallestNumber | |
def initialize(target:, formatter: PositiveFormatter.new) | |
@target = target | |
@formatter = formatter | |
end | |
# Let the formatter do its job. Just ask it | |
def to_s | |
formatter.format(target) | |
end | |
private | |
attr_reader :target, :formatter | |
end | |
class SmallestArrNumber | |
# it was not requested a limit of the range that an element of the array should have | |
# therefore I am adding the possibility to this be passed, otherwise default to 500. | |
def initialize(array_size: 1, limit: 500) | |
@target_arr = Array.new(array_size){ rand(1..limit) } | |
end | |
def call | |
smallest_number = fetch_smallest_number(target_arr) | |
missing_smallest_number = smallest_number - 1 | |
formatter = missing_smallest_number > 0 ? PositiveFormatter.new : NonPositiveFormatter.new | |
puts SmallestNumber.new(target: missing_smallest_number, formatter: formatter) | |
end | |
# Sort array by small to greater value so that we have elements in order | |
# and the smallest number on it will be at its first position | |
def fetch_smallest_number(arr) | |
# one could implement a better sorting algoritm here instead of ruby default algoritm for its sort method | |
arr.sort.first | |
end | |
private | |
attr_reader :target_arr | |
end | |
# loading it in your console | |
# i.e cd into folder of the script: cd folder | |
# irb -r ./script_file_name | |
# the console will be opened with the file already loaded. | |
# > SmallestArrNumber.new(array_size: 20).call |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
A simple form would be: