回顾:有上限的库存
Coddy 面向 JavaScript 开发者的 PHP 课程的第 32 课,共 48 课。
挑战
简单输入为 [initial,removals],initial 和 removals 均为非负数。Stock(initial) 用于存储 units。remove(amount):bool 在 amount 超过剩余数量时返回 false,且不改变 units;否则减去 amount 并返回 true。remaining():int 用于读取 units。驱动程序会输出 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";
面向 JavaScript 开发者的 PHP中的所有课
自己练习: PHP 在线编译器