Menu
CoddyTech

Final: port a queue model

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

C# reference program

#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());
 }
}

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 C# Developers

Practice on your own: Online PHP compiler