返回首页 - Notes - 2017

可以喝多少瓶可乐


源代码

#!/usr/bin/env ruby

# 计算可以喝多少瓶可乐

PRICE  = 2  # 2元买1瓶
BOTTLE = 2  # 2个空瓶换1瓶
LID    = 4  # 4个瓶盖换1瓶

def calc(money, bottles = 0, lids = 0, times = 0)
  return [money, bottles, lids, times] if money < PRICE && bottles < BOTTLE && lids < LID

  if money >= PRICE
    drinks = (money / PRICE).to_i
    times += drinks
    money = money - drinks * PRICE
    lids += drinks
    bottles += drinks
  end

  if bottles >= BOTTLE
    drinks = (bottles / BOTTLE).to_i
    times += drinks
    bottles -= drinks * BOTTLE
    bottles += drinks
    lids += drinks
  end

  if lids >= LID
    drinks = (lids / LID).to_i
    times += drinks
    bottles += drinks
    lids -= drinks * LID
    lids += drinks
  end

  calc(money, bottles, lids, times)
end

result = calc(money = ARGV.shift.to_i)

puts <<-LONGSTR
#{money} 元可以喝 #{result[3]} 瓶可乐
剩余银子 #{result[0]} 元
剩余空瓶 #{result[1]} 个
剩余瓶盖 #{result[2]} 个
LONGSTR

使用方法

  1. chmod a+x cocacola_calc
  2. ./cocacola_calc 金额

date:2017-01-23