Created
May 25, 2018 16:56
-
-
Save vgarro/1adbc5e8df82a12cd305ccb9418ce2ff to your computer and use it in GitHub Desktop.
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
# https://dev.to/r0f1/write-a-simple-but-impactful-script-7ba | |
# Write a script that produces all possible 4-digit numbers (0000...9999), | |
# then put them into a random order and | |
# save the output into a text file | |
class ExcerciseOrquestrator | |
attr_reader :output_file_name | |
def initialize(output_file_name) | |
@output_file_name = output_file_name | |
end | |
def process(digits) | |
output = NumberGenerator.new(digits).process | |
write_to_file(output) | |
end | |
private | |
def write_to_file(output) | |
open_file do |file| | |
output.each do |row| | |
file.write("#{row}\n") | |
end | |
end | |
end | |
def open_file | |
File.open(output_file_name, 'w') do |file| | |
yield(file) | |
end | |
end | |
end | |
class NumberGenerator | |
attr_reader :digits | |
def initialize(digits) | |
@digits = digits | |
end | |
def max_number | |
(10 ** digits) -1 | |
end | |
def first_number | |
0 | |
end | |
def process | |
arr = do_generate | |
(arr || []).shuffle | |
end | |
private | |
def do_generate | |
(first_number..max_number).each_with_object([]) do |digit, acc| | |
acc << digit.to_s.rjust(digits, '0') | |
end | |
end | |
end | |
ExcerciseOrquestrator.new('randon_numbers').process(4) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment