Menu
CoddyTech

最终挑战:移植队列模型

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

challenge icon

挑战

简单

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

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

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

Rust 参考程序

use std::collections::VecDeque;
struct WorkQueue{items:VecDeque<String>}
impl WorkQueue{
    fn new(initial:Vec<String>)->Self{Self{items:initial.into()}}
    fn push(&mut self,text:String){self.items.push_back(text);}
    fn pop(&mut self)->Option<String>{self.items.pop_front()}
    fn size(&self)->usize{self.items.len()}
}
fn main(){
    let mut q=WorkQueue::new(vec!["a".into(),"b".into()]);
    let mut output=vec![q.pop().unwrap_or_else(||"EMPTY".into())];
    q.push("c".into());output.push(q.pop().unwrap_or_else(||"EMPTY".into()));
    println!("{}|{}",output.join(","),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";

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

自己练习: PHP 在线编译器