loops - Ruby program to distribute books among kids equally -


imagine have 5 different books, books = ['a','b','c','d','e'], , want share among 3 children kids = [k1,k2,k3]. use zip , cycle function operation,

books.zip(kids.cycle) 

so output

{"a"=>"k1", "b"=>"k2", "c"=>"k3", "d"=>"k1", "e"=>"k2"} 

next day, have 4 books, books = ['f','g','h','i'], time iwant distribute these books among same 3 kids equally end of second day, ie. 3 kids should have 3 books each @ end of second day.

how achive this?

first need think structures going use storing input , output data intermediary data if needed.

with hashes , arrays can achieve arbitrarily complex structure. profitable future encapsulate data within classes using oop paradigm.

with hashes , arrays this:

#init data input kids = ['alice', 'bob', 'kate'] books_over_days = [   [ 'book1', 'book2', 'book3'],   [ 'book4', 'book5'] ]  #init data storing output kids_to_books = {} kids.each {|kid| kids_to_books[kid] = []}  books_over_days.each |books|   kids.each {|kid| kids_to_books[kid] << books.sample}     end   puts kids_to_books.inspect 

you use encapsulation , classes write differently + books generator data dynamically generated instead of declaring statically. this

class kid   attr_reader :books, :name   def initialize(name)     @name = name     @books = []   end    def add_book(book)     @books << book   end end  book = struct.new(:name)  class booksgenerator   attr_reader :books  def initialize(factor)     @books = []     @factor = factor   end    def generate     0.upto(random.rand(@factor)) {|e| @books << "book#{random.rand(@factor*@factor)}"}     @books.uniq!   end end  days_n = 3  generator = booksgenerator.new(5) kids = [kid.new("alice"), kid.new("bob"), kid.new("kate")] days_n.times   generator.generate   kids.each { |k| k.add_book(generator.books.sample)} end  puts kids.inspect 

without more details hard more.


Comments