最終課題:キューモデルを移植する
Coddyの「R開発者のためのPHP」コースのレッスン 48/48。
チャレンジ
簡単入力は[initial,operations]です。このタスクで提供されるソースの参照プログラムを移植してください。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__を使用します。
Rの参照プログラム
WorkQueue <- function(initial) {
items <- as.list(initial)
list(
push=function(text) {items[[length(items)+1L]] <<- text; invisible(NULL)},
pop=function() {
if(length(items)==0L) return(NULL)
first <- items[[1L]]
items <<- items[-1L]
first
},
size=function() length(items)
)
}
render <- function(value) if(is.null(value)) "EMPTY" else value
q <- WorkQueue(c("a","b"))
output <- render(q$pop())
q$push("c");output <- c(output,render(q$pop()))
cat(paste(output,collapse=","),"|",q$size(),"\n",sep="")
自分で試してみよう
<?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";
R開発者のためのPHPのすべてのレッスン
自分で練習してみよう: PHPオンラインコンパイラ