Menu
CoddyTech

回顾:有上限的库存

Coddy 面向 C# 开发者的 PHP 课程的第 32 课,共 48 课。

challenge icon

挑战

简单

输入为 [initial,removals],initial 和 removals 均为非负数。Stock(initial) 用于存储库存单位数。remove(amount):bool 会在 amount 超过剩余单位数时返回 false,且不更改单位数;否则会扣除相应数量并返回 true。remaining():int 用于读取单位数。驱动程序会输出 remaining:successCount。

提供的 main 脚本会从标准输入读取一个 JSON 值,检查指定的公共 API,并输出结果。请实现模块声明,不要打印内容;不要替换启动器,也不要从模块中读取输入。输入符合所述类型和范围。

编辑 Stock.php。main.php 是锁定的入口文件。依赖项使用 require_once __DIR__ 和相对文件名。

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/Stock.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function stockReport(array $i):string{$s=new Stock($i[0]);$ok=0;foreach($i[1] as $n)if($s->remove($n))$ok++;return $s->remaining().":".$ok;}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$s=new Stock(4);ensure(!$s->remove(5)&&$s->remaining()===4,"reject atomic");ensure($s->remove(2)&&$s->remaining()===2,"remove");
echo stockReport($input),"\n";

面向 C# 开发者的 PHP中的所有课

自己练习: PHP 在线编译器