Menu
CoddyTech

Final: port a queue model

Lesson 48 of 48 in Coddy's PHP for GDScript Developers course.

challenge icon

Challenge

Easy

Input is [initial,operations]. Port the source reference program supplied in this task. WorkQueue(initial array) stores string items. push(string):void appends; pop():?string removes and returns the oldest or null when empty; size():int counts remaining. Operations are [push,text] or [pop]. Driver prints popped values separated by commas, using EMPTY for null, then |size. Input items contain ASCII letters only.

The supplied main script reads one JSON value from standard input, checks the named public APIs, and prints the result. Implement the module declarations without printing; do not replace the launcher or read input from a module. Input satisfies the stated types and bounds.

Edit WorkQueue.php. main.php is the locked entry file. Dependencies use require_once __DIR__ with a relative filename.

GDScript reference program

extends SceneTree
class WorkQueue:
    var items: Array
    func _init(initial: Array):
        items = initial.duplicate()
    func push(text: String) -> void:
        items.append(text)
    func pop():
        return null if items.is_empty() else items.pop_front()
    func size() -> int:
        return items.size()
func _init():
    var queue = WorkQueue.new(["a", "b"])
    var output = [queue.pop()]
    queue.push("c")
    output.append(queue.pop())
    var rendered = PackedStringArray()
    for value in output:
        rendered.append("EMPTY" if value == null else value)
    print(",".join(rendered) + "|" + str(queue.size()))
    quit()

Try it yourself

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

All lessons in PHP for GDScript Developers

Practice on your own: Online PHP compiler