최종: 큐 모델 포팅하기
Coddy의 C# 개발자를 위한 PHP 코스 레슨. 48개 중 48번째.
챌린지
쉬움입력은 [초기값, 연산]입니다. 이 과제에서 제공하는 참조 프로그램을 포팅하세요. WorkQueue(initial array)는 문자열 항목을 저장합니다. push(string):void는 항목을 추가하고, pop():?string은 가장 오래된 항목을 제거해 반환하며 비어 있으면 null을 반환하고, size():int는 남은 항목 수를 셉니다. 연산은 [push,text] 또는 [pop]입니다. 드라이버는 꺼낸 값을 쉼표로 구분해 출력하고, null에는 EMPTY를 사용한 다음 |size를 출력합니다. 입력 항목에는 ASCII 문자만 포함됩니다.
제공된 메인 스크립트는 표준 입력에서 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 컴파일러