Skip to content

Instantly share code, notes, and snippets.

@ttreitlinger
Created March 10, 2011 14:42
Show Gist options
  • Save ttreitlinger/864187 to your computer and use it in GitHub Desktop.
Save ttreitlinger/864187 to your computer and use it in GitHub Desktop.
class Table
attr_reader :num_diners, :table_no
def initialize table_no, num_diners
@table_no = table_no
@num_diners = num_diners
end
def to_string
"Table #{@table_no} has #{@num_diners} diners"
end
def contented?
if rand(2) > 0
return true
else
return false
end
end
end
class Waiter
def initialize tables
@tables = tables
end
end
class CountingWaiter < Waiter
attr_reader :no_of_diners
def count_diners
@no_of_diners = 0
@tables.each { |table| @no_of_diners += table.num_diners}
end
end
class ContentmentWaiter < Waiter
attr_reader :unhappy_tables
def get_unhappy_tables
@unhappy_tables = []
@tables.each do |table|
if !table.contented?
@unhappy_tables << table.table_no
end
end
end
end
# create 10 tables
tables = []
1..10.times do |i|
tables << Table.new(i, rand(3) + 2)
end
tables.each { |t| puts t.to_string}
# counting waiter goes to each table and adds up number of diners
waiter = CountingWaiter.new tables
waiter.count_diners
puts "Total number of diners: #{waiter.no_of_diners}"
# contentment waiter goes to each table and stores table number of all unhappy tables
waiter = ContentmentWaiter.new tables
waiter.get_unhappy_tables
puts "Unhappy tables: #{waiter.unhappy_tables}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment