最终:库存端口
Coddy 面向 PHP 开发者的 GDScript 课程的第 47 课,共 48 课。
挑战
简单移植 PHP 参考实现:输入单词,返回按字母顺序排序、以逗号连接的单词=count 对;如果没有单词,则返回 none。单词均为小写 ASCII 字符,重复单词分别计数。不要更改调用方的输入。
输入是 stdin 上的一个 JSON 数组。锁定的 main 会解析它、调用公开 API,并打印 result=,后面接返回的文本和一个换行符。任何辅助函数都不应打印内容。输入用例前会运行独立的固定探测,以验证所需的 API 行为;这些探测不会限制实现风格。
你的代码写在 exercise.gd 中。main.gd 包含提供的输入/输出代码,不能编辑。每个 class_name 类型都要放在对应名称的文件中。
完整的 PHP 参考程序。每个文件都会完整展示;使用 PHP 8.3 CLI 运行 main.php,并传入与本题相同的 JSON 数组输入。
PHP 文件 functions.php:
<?php
declare(strict_types=1);
function inventory(array $words): string {
$counts=[];
foreach($words as $word) $counts[$word]=($counts[$word]??0)+1;
ksort($counts,SORT_STRING);
$result=[];
foreach($counts as $word=>$count) $result[]=$word."=".$count;
return $result ? implode(",",$result) : "none";
}
PHP 文件 main.php:
<?php
declare(strict_types=1);
require_once __DIR__."/functions.php";
$words=json_decode(stream_get_contents(STDIN),true,512,JSON_THROW_ON_ERROR);
echo "result=",inventory($words),"\n";
亲手试试
extends Node
func contract_ok(data: Array) -> bool:
return true
func _ready() -> void:
var data: Array = JSON.parse_string(OS.read_string_from_stdin())
if not contract_ok(data):
print("API_CONTRACT_FAILED")
return
print("result=" + Exercise.solve(data))
面向 PHP 开发者的 GDScript中的所有课
自己练习: GDScript 在线编译器