Menu
CoddyTech

最終課題:テキストパイプラインを移植する

Coddyの「R開発者のためのPHP」コースのレッスン 47/48。

challenge icon

チャレンジ

簡単

入力は文字列のリストです。このタスクで提供されている参照元プログラムを移植してください。abbreviations は空文字列を取り除き、残った各文字列の最初の ASCII 文字を取り出して大文字にし、ドットでつなげます。順序を保持し、空でない文字列がない場合は none を返します。すべての入力は ASCII です。

提供されているメインスクリプトは、標準入力から JSON 値を1つ読み取り、指定された公開 API を確認して、結果を出力します。出力を行わずにモジュール宣言を実装してください。ランチャーを置き換えたり、モジュールから入力を読み取ったりしないでください。入力は、指定された型と上限を満たしています。

Functions.php を編集してください。main.php は変更できないエントリーファイルです。依存関係の読み込みには、相対ファイル名を指定した require_once __DIR__ を使用します。

R の参照元プログラム

# Raw vectors represent ASCII strings, including possible zero bytes.
abbreviations <- function(words) {
    output <- raw()
    found <- FALSE
    for(word in words) {
        if(length(word)==0L) next
        if(found) output <- c(output,as.raw(46))
        first <- as.integer(word[1L])
        if(first>=97L && first<=122L) first <- first-32L
        output <- c(output,as.raw(first))
        found <- TRUE
    }
    if(found) output else charToRaw("none")
}
words <- lapply(c("red","","green","blue"),charToRaw)
cat(rawToChar(abbreviations(words)),"\n",sep="")

自分で試してみよう

<?php
declare(strict_types=1);
require_once __DIR__."/Functions.php";
function ensure(bool $ok,string $message):void{if(!$ok)throw new RuntimeException("API: ".$message);}

$input=json_decode(trim(stream_get_contents(STDIN)),true,512,JSON_THROW_ON_ERROR);
ensure(abbreviations(["a","","b"])==="A.B" && abbreviations([])==="none","port pipeline");
echo abbreviations($input),"\n";

R開発者のためのPHPのすべてのレッスン

自分で練習してみよう: PHPオンラインコンパイラ