Menu
CoddyTech

Dự án: phân tích mục thời gian

Bài học 43 trên 48 trong khóa học PHP dành cho lập trình viên C# của Coddy.

challenge icon

Thử thách

Dễ

Đầu vào [1,row]. Hoàn thành Parser::parse(string):?Entry. Chấp nhận chính xác các chữ cái ASCII viết thường, dấu hai chấm và từ một đến ba chữ số, không có khoảng trắng ở đầu hoặc cuối. Trả về Entry(name,minutes) hoặc null. Chấp nhận số 0 ở đầu. Entry đã được cung cấp. Tạm thời để nguyên các chỗ giữ chỗ cho những giai đoạn sau.

Tệp main được cung cấp đọc một giá trị JSON từ đầu vào tiêu chuẩn, kiểm tra các API công khai được nêu tên và in kết quả. Hãy triển khai các khai báo module mà không in gì; đừng thay thế trình chạy hoặc đọc đầu vào từ một module. Đầu vào đáp ứng các kiểu và giới hạn đã nêu.

Chỉnh sửa Entry.php, Parser.php, Ledger.php, Reporter.php. main.php là tệp điểm vào đã khóa. Các phần phụ thuộc dùng require_once __DIR__ cùng với tên tệp tương đối.

Tự làm thử

<?php
declare(strict_types=1);
require_once __DIR__."/Entry.php";
require_once __DIR__."/Parser.php";
require_once __DIR__."/Ledger.php";
require_once __DIR__."/Reporter.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}
function projectReport(array $input):string{
 [$stage,$data]=$input;
 if($stage===1){$e=(new Parser())->parse($data);return $e===null?"invalid":$e->name.":".$e->minutes;}
 if($stage===2){$l=new Ledger();foreach($data[0] as [$name,$minutes])$l->add(new Entry($name,$minutes));return (string)$l->total($data[1]);}
 if($stage===3){$l=new Ledger();foreach($data as [$name,$minutes])$l->add(new Entry($name,$minutes));$out=$l->lines();return $out===[]?"empty":implode("\n",$out);}
 return (new Reporter())->report($data);
}
$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
$stage=$input[0];$parser=new Parser();$e=$parser->parse("tea:007");ensure($e instanceof Entry && $e->name==="tea" && $e->minutes===7 && $parser->parse("tea:-1")===null && $parser->parse(" tea:2")===null,"parser API");
if($stage>=2){$l=new Ledger();$l->add(new Entry("b",4));$l->add(new Entry("b",3));$l->add(new Entry("a",0));ensure($l->total("b")===7 && $l->total("x")===0,"aggregation API");}
if($stage>=3){ensure($l->lines()===["a:0","b:7"] && $l->lines()===["a:0","b:7"],"ordered snapshot");}
if($stage>=4){$r=new Reporter();ensure($r->report(["z:3","bad","z:2"])==="z:5" && $r->report([])==="empty","fresh report state");}
echo projectReport($input),"\n";

Tất cả bài học trong PHP dành cho lập trình viên C#

Tự luyện tập: Trình biên dịch PHP online