こんにちは。ぽこです!
今回は、PHPでの競技プログラミングを行う際に使える、便利なclassを紹介します。
入力を受け取るclass
まずは、入力を受け取るためのclassです。
class Scanner {
private $arr = [];
private $count = 0;
private $pointer = 0;
public function next() {
if($this->pointer >= $this->count) {
$str = trim(fgets(STDIN));
$this->arr = explode(' ', $str);
$this->count = count($this->arr);
$this->pointer = 0;
}
$result = $this->arr[$this->pointer];
$this->pointer++;
return $result;
}
public function hasNext() {
return $this->pointer < $this->count;
}
public function nextInt() {
return (int)$this->next();
}
public function nextDouble() {
return (double)$this->next();
}
}JavaのScannerのようなものになっています。
解説
内容を見てみましょう。
public function next() {
if($this->pointer >= $this->count) {
$str = trim(fgets(STDIN));
$this->arr = explode(' ', $str);
$this->count = count($this->arr);
$this->pointer = 0;
}
$result = $this->arr[$this->pointer];
$this->pointer++;
return $result;
}next()について、簡単に説明すると、
まず 3~6行目で、入力された1行目を取得し、スペース区切りで値を配列に格納します。
そして、その配列を$pointerを使って順々に返します。
その行に値がなくなったら(配列の最後まで行ったら)、次の行を読んでまた3~6行目の処理を行います。
これを、呼び出されるごとに行います。
一つ一つの行を説明すると、次のようになります。
2行目で、 その行の値がもうない場合に3~6行目の処理に移ります。
3行目で、入力された文字列(改行まで)を$strに格納します。
4行目で、 $str を空白で区切り、$arrに格納します。
5行目で、 $arr の数(1行に入力された値の数)を$countに登録します。
6行目で、$pointerを0にします。
8行目で、$resultに$arrの$pointer個目の値を格納します。
9行目で、 $pointerの値を一つ増やします。
10行目で、 $resultの値を返します。
出力をするclass
class out {
public static function println($str = "") {
echo $str . PHP_EOL;
}
}出力を行うclassは簡単ですが、最後に改行を行うようになっています。
使い方について、詳しくは次で紹介しているので、そちらも併せて確認してください。

