Menu
CoddyTech

最終課題:キューモデルを移植する

Coddyの「Lua開発者のための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値を1つ読み取り、指定された公開APIを確認して、結果を出力します。出力せずにモジュール宣言を実装してください。ランチャーを置き換えたり、モジュールから入力を読み取ったりしないでください。入力は指定された型と範囲を満たしています。

WorkQueue.phpを編集してください。main.phpはロックされたエントリーファイルです。依存関係では、相対ファイル名を指定したrequire_once __DIR__を使用します。

Luaの参照プログラム

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

Lua開発者のためのPHPのすべてのレッスン

自分で練習してみよう: PHPオンラインコンパイラ