Menu
CoddyTech

最终:库存移植

Coddy Ruby for C++ Developers 课程的第 47 课,共 48 课。

challenge icon

挑战

简单

移植参考程序。Stock 初始值为 0;只有结果库存非负时,change(delta) 才接受变更,并返回 true 或 false。quantity 用于读取库存。Inventory.change(code,delta) 按代码应用变更,只有变更成功时才创建该代码。report 按代码字母顺序返回正数库存,格式为 code:quantity 对,若没有则返回 none。输入由 code delta 对组成,每行一对。每次变更输出一个布尔值,然后输出报告。将 Stock 和 Inventory 分别放在各自的文件中。

让 solve(input) 返回文本,不要打印。锁定的驱动程序会打印返回的文本,并在末尾添加一个换行符,还会独立检查所需的公共 API。

你的代码应放在 exercise.rb、stock.rb、inventory.rb 中。main.rb 包含提供的输入/输出代码,不能编辑。

输入范围:最多 1000 行数据。库存代码只包含小写 ASCII 字母,每个库存增量介于 -1000000 和 1000000 之间。对于传感器移植,第一行的限制值介于 -1000000 和 1000000 之间;令牌有效性遵循上述解析器约定。

C++ 参考程序。使用所需的 Ruby API 实现与其一致的行为。

#include <iostream>
#include <sstream>
#include <string>
#include <map>
class Stock {
    long long quantity_=0;
public:
    bool change(long long delta) {
        long long next=quantity_+delta;
        if(next<0)return false;
        quantity_=next;return true;
    }
    long long quantity()const{return quantity_;}
};
class Inventory {
    std::map<std::string,Stock> items;
public:
    bool change(const std::string& code,long long delta) {
        auto found=items.find(code);
        if(found!=items.end())return found->second.change(delta);
        Stock stock;
        if(!stock.change(delta))return false;
        items.emplace(code,stock);return true;
    }
    std::string report()const {
        std::ostringstream out;bool first=true;
        for(const auto& entry:items)if(entry.second.quantity()>0) {
            if(!first)out<<' ';
            first=false;out<<entry.first<<':'<<entry.second.quantity();
        }
        return first?"none":out.str();
    }
};
int main() {
    Inventory inventory;std::string line;
    while(std::getline(std::cin,line)) {
        std::istringstream row(line);std::string code;long long delta;
        if(row>>code>>delta)std::cout<<std::boolalpha<<inventory.change(code,delta)<<'\n';
    }
    std::cout<<inventory.report()<<'\n';
}

亲手试试

require_relative 'exercise'
require_relative 'stock'
require_relative 'inventory'
def check(value)
  raise 'Public API check failed' unless value
end
s = Stock.new
check(!s.change(-1) && s.quantity == 0 && s.change(4) && !s.change(-5) && s.quantity == 4)
i = Inventory.new
check(!i.change("x", -2) && i.report == "none")
check(i.change("b", 2) && i.change("a", 1) && i.report == "a:1 b:2")

puts solve(STDIN.read)

Ruby for C++ Developers中的所有课

自己练习: Ruby 在线编译器