Menu
CoddyTech

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

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

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

C#の参照プログラム

#nullable enable
using System;
using System.Collections.Generic;
using System.Linq;

class Program {
class WorkQueue{
 private readonly Queue<string> items;
 public WorkQueue(IEnumerable<string> initial){items=new Queue<string>(initial);}
 public void Push(string item){items.Enqueue(item);}
 public string? Pop(){return items.Count==0?null:items.Dequeue();}
 public int Size(){return items.Count;}
}
 static void Main() {
  var q=new WorkQueue(new[]{"a","b"});var output=new List<string?>{q.Pop()};q.Push("c");output.Add(q.Pop());Console.WriteLine(string.Join(",",output)+"|"+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";

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

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