Menu
CoddyTech

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

Coddyの「Go開発者のためのPHP」コースのレッスン 48/48。

challenge icon

チャレンジ

簡単

入力は[初期値,操作]です。この課題で提供される参照プログラムを移植してください。WorkQueue(initial array)は文字列項目を格納します。push(string):voidは末尾に追加し、pop():?stringは最も古い項目を削除して返します。空の場合はnullを返します。size():intは残りの項目数を数えます。操作は[push,text]または[pop]です。ドライバーは、取り出した値をコンマ区切りで出力し、nullにはEMPTYを使った後、|sizeを出力します。入力項目に含まれるのはASCII文字のみです。

提供されたメインスクリプトは標準入力からJSON値を1つ読み取り、指定された公開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オンラインコンパイラ