Menu
CoddyTech

Final: port a queue model

Lesson 48 of 48 in Coddy's PHP for Ruby 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.

Ruby reference program

class WorkQueue
  def initialize(initial); @items = initial.dup; end
  def push(item); @items << item; end
  def pop; @items.shift; end
  def size; @items.length; end
end
q = WorkQueue.new(["a", "b"])
out = [q.pop]; q.push("c"); out << q.pop
puts out.join(",") + "|" + q.size.to_s

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 Ruby Developers

Practice on your own: Online PHP compiler