最终挑战:迁移队列模型
Coddy 面向 Go 开发者的 PHP 课程的第 48 课,共 48 课。
挑战
简单输入格式为 [initial,operations]。移植本题提供的源代码参考程序。WorkQueue(initial 数组)用于存储字符串项。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__ 和相对文件名。
Go 参考程序
package main
import ("fmt";"strings")
type WorkQueue struct{items []string}
func NewWorkQueue(initial []string)*WorkQueue{
return &WorkQueue{items:append([]string(nil),initial...)}
}
func(q *WorkQueue)Push(text string){q.items=append(q.items,text)}
func(q *WorkQueue)Pop()(string,bool){
if len(q.items)==0{return "",false}
first:=q.items[0]
q.items[0]=""
q.items=q.items[1:]
return first,true
}
func(q *WorkQueue)Size()int{return len(q.items)}
func render(value string,ok bool)string{if !ok{return "EMPTY"};return value}
func main(){
q:=NewWorkQueue([]string{"a","b"})
out:=[]string{render(q.Pop())}
q.Push("c");out=append(out,render(q.Pop()))
fmt.Printf("%s|%d\n",strings.Join(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";
面向 Go 开发者的 PHP中的所有课
自己练习: PHP 在线编译器