Skip to content

Instantly share code, notes, and snippets.

@ttreitlinger
Created March 10, 2011 15:01
Show Gist options
  • Save ttreitlinger/864216 to your computer and use it in GitHub Desktop.
Save ttreitlinger/864216 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
def accept visitor
visitor.visitTable self
end
end
class DutchTable
attr_reader :aantal_gasten, :table_no
def initialize table_no, num_diners
@table_no = table_no
@aantal_gasten = num_diners
end
def to_string
"Table #{@table_no} has #{@aantal_gasten} diners (Dutch)"
end
def tevreden?
if rand(2) > 0
return true
else
return false
end
end
def accept visitor
visitor.visitDutchTable self
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| table.accept self}
end
def visitTable table
@no_of_diners += table.num_diners
end
def visitDutchTable table
@no_of_diners += table.aantal_gasten
end
end
class ContentmentWaiter < Waiter
attr_reader :unhappy_tables
def get_unhappy_tables
@unhappy_tables = []
@tables.each { |table| table.accept self }
end
def visitTable table
if !table.contented?
@unhappy_tables << table.table_no
end
end
def visitDutchTable table
if !table.tevreden?
@unhappy_tables << table.table_no
end
end
end
# create 10 tables
tables = []
1..10.times do |i|
if rand(2) == 0
tables << Table.new(i, rand(3) + 2)
else
tables << DutchTable.new(i, rand(3) + 2)
end
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