Menu
CoddyTech

最终挑战:迁移队列模型

Coddy 面向 Luau 开发者的 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 字母。

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

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

Luau 参考程序

local WorkQueue={}
WorkQueue.__index=WorkQueue
function WorkQueue.new(initial)
    local items={}
    for i,value in ipairs(initial) do items[i]=value end
    return setmetatable({items=items},WorkQueue)
end
function WorkQueue:push(text) self.items[#self.items+1]=text end
function WorkQueue:pop()
    if #self.items==0 then return nil end
    return table.remove(self.items,1)
end
function WorkQueue:size() return #self.items end
local q=WorkQueue.new({"a","b"})
local out={q:pop() or "EMPTY"}
q:push("c");out[#out+1]=q:pop() or "EMPTY"
print(table.concat(out,",").."|"..q:size())

亲手试试

<?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";

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

自己练习: PHP 在线编译器