Skip to content

Instantly share code, notes, and snippets.

@smileart
Created December 11, 2016 20:47
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 smileart/e0909b5211345496b592f21b9051f1fd to your computer and use it in GitHub Desktop.
Save smileart/e0909b5211345496b592f21b9051f1fd to your computer and use it in GitHub Desktop.
HackerRank STDIN data loader
class HackerDataLoader
SKIP_WORDS = [:ignore, :skip, :next].freeze
def self.load(input, quantifiers, format = {})
io = $stdin === input ? input : StringIO.new(input)
result = {}
format.each_pair do |name, val|
data = []
if quantifiers
n = io.gets
1.step(n.to_i, 1) { |i| data << io.gets }
else
shell_skip = SKIP_WORDS.include?(val)
while row = io.gets
break if shell_skip
data << row
end
next if shell_skip
end
val[:each] = [val[:each]] if val[:each] && !val[:each].respond_to?(:each)
val[:all] = [val[:all]] if val[:all] && !val[:all].respond_to?(:each)
data.map! do |row|
sub_result = row
val[:each].each { |tr| sub_result = tr.(sub_result) }
sub_result
end if val[:each]
val[:all].each do |tr|
data = tr.(data)
end if val[:all]
data = data.first if data.length == 1
result[name] = data
end
result
end
end
# 🚧 2 data sets with lines quantifiers 🚧
#
# input = <<-DATA
# 3
# row 1
# row 2
# row 3
# 1
# 9 13 2 8
# DATA
#
# HackerDataLoader.load(input, {
# rows: {
# each: ->(row) { row.strip },
# all: ->(rows) { rows.join(', ') }
# },
# numbers: {
# each: [
# ->(row) { row.split(' ').map(&:to_i) }
# ]
# }
# })
# 🚧 simple numbers list 🚧
#
# input = <<-DATA
# 13
# 42
# DATA
#
# HackerDataLoader.load(input, false, {
# integers: {
# each: [
# ->(row) { row.to_i }
# ]
# }
# })
# 🚧 useless quantifier and numbers in a row 🚧
#
# input = <<-DATA
# 6
# 1 2 3 4 10 11
# DATA
#
# HackerDataLoader.load(input, false, {
# amount: :skip,
# integers: {
# each: [
# ->(row) { row.split(' ').map(&:to_i) }
# ]
# }
# })
# 🚧 quantifier + 3 rows of integers 🚧
#
# input = <<-DATA
# 3
# 11 2 4
# 4 5 6
# 10 8 -12
# DATA
#
# HackerDataLoader.load(input, true, {
# integers: {
# each: ->(row) { row.split(' ').map(&:to_i) },
# all: ->(arrays) { result = []; arrays.each { |a| result << a } }
# }
# })
# 🚧 1 row of text 🚧
# ℹ️ + named argument usage exmaple
#
# input = <<-DATA
# 07:05:45PM
# DATA
#
# data = HackerDataLoader.load(input, false, {
# time: {
# each: ->(row) { row.strip },
# }
# })
#
# def time(time:)
# puts time
# end
#
# time(**data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment