Psst.. new poll here.
Psst.. new forums here.
Microsoft is blocking us again (TY IP Reputation!) so just use oauth login instead. :)
Paste
Pasted as Ruby by swol1 ( 7 years ago )
# Дан список товаров:
# | Код | Название | Цена |
# |:---:|:----------:|:-----:|
# | CC | Кока-Кола | $1.50 |
# | PC | Пепси Кола | $2.00 |
# | WA | Вода | $0.85 |
# Для некоторых товаров есть определенные правила дисконтирования:
# 1. Если покупаете 3 и более бутылки Пепси Колы, то стоимость для каждой бутылки Пепси Колы снижается на 20%.
# 2. Если покупаете одну бутылку Кока Колы, то вторая даётся бесплатно.
# Реализуйте класс Checkout и необходимые дополнительные классы, которые считает общую стоимость покупки.
# Пример использования:
# ```ruby
# co = Checkout.new(pricing_rules)
# co.add(item)
# p co.total
# ```
# Примеры:
# ```
# Input: CC PC WA
# Output: $4.35
class Item
attr_reader :code, :price
def initialize(items)
@code = items[0]
@price = items[2]
end
end
class Checkout
def initialize(data)
@items = data.map {
|item| Item.new(item)
}
@total = 0
end
def add(user_codes)
@user_order = []
user_codes.each do |user_code|
@user_order << @items.select { |item| item.code == user_code }
end
calculate_price(@user_order)
end
def calculate_price(user_order)
pepsi_amount = 0
cola_amount = 0
user_order.each do |order|
order.each do |item|
pepsi_amount += 1 if item.code == "PC"
@total += item.price if item.code == "PC"
end
end
@total = @total * 0.8 if pepsi_amount > 2
user_order.each do |order|
order.each do |item|
cola_amount += 1 if item.code == "CC"
if cola_amount > 1 && item.code == "CC"
@total += 0
else
@total += item.price unless item.code == "PC"
end
cola_amount = 0 if cola_amount > 1
end
end
end
def total
@total.round(2)
end
def to_s
"Output: $#{total}"
end
end
array = [
[ "CC", "Coca-Cola", 1.50 ],
[ "CC", "Pepsi", 2.00 ],
[ "WA", "Water", 0.85 ]
]
co = Checkout.new(array)
print "Input: "
user_input = STDIN.gets.chomp
user_codes = user_input.split(' ')
co.add(user_codes)
puts co
Revise this Paste
Parent: 97181
Children: 97183