Menu
CoddyTech

最终挑战:移植队列模型

Coddy 面向 Ruby 开发者的 PHP 课程的第 48 课,共 48 课。

challenge icon

挑战

简单

输入格式为 [initial,operations]。请移植本挑战提供的源代码参考程序。WorkQueue(initial array) 用于存储字符串项。push(string):void 会追加项;pop():?string 会移除并返回最早加入的项,如果队列为空则返回 null;size():int 会统计剩余项数。操作格式为 [push,text] 或 [pop]。驱动程序会用逗号分隔弹出的值,null 对应 EMPTY,之后输出 |size。输入项只包含 ASCII 字母。

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

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

Ruby 参考程序

class WorkQueue
  def initialize(initial); @items = initial.dup; end
  def push(item); @items << item; end
  def pop; @items.shift; end
  def size; @items.length; end
end
q = WorkQueue.new(["a", "b"])
out = [q.pop]; q.push("c"); out << q.pop
puts out.join(",") + "|" + q.size.to_s

亲手试试

<?php
declare(strict_types=1);
require_once __DIR__."/WorkQueue.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function queueReport(array $i):string{$q=new WorkQueue($i[0]);$out=[];foreach($i[1] as $op){if($op[0]==="push")$q->push($op[1]);else $out[]=$q->pop()??"EMPTY";}return implode(",",$out)."|".$q->size();}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$a=new WorkQueue(["a"]);$b=new WorkQueue([]);ensure($a->pop()==="a" && $a->pop()===null && $b->size()===0,"queue independence");$a->push("z");ensure($a->size()===1 && $a->pop()==="z","queue API");
echo queueReport($input),"\n";

面向 Ruby 开发者的 PHP中的所有课

自己练习: PHP 在线编译器