9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

PPAPテストをPHPで

Last updated at Posted at 2016-11-06

PPAPテストをPHPで

概要

環境

  • PHP 7.1.0RC5

実装

シンプルに

<?php
$ppap = [
	'ペン',
	'パイナッポー',
	'アッポー',
	'ペーン',
];

while (true) {
	shuffle($ppap);
	$result = implode('', $ppap);
	echo $result . PHP_EOL;;
	if ($result === 'ペンパイナッポーアッポーペーン') {
		break;
	}
}
echo '\(^o^)/ピコ!' . PHP_EOL;

iterator

<?php
class PPAP implements Iterator
{
    public $ppap = [
        'ペン',
        'パイナッポー',
        'アッポー',
        'ペーン',
    ];

    public function current()
    {
        shuffle($this->ppap);                                                                                                                                   
        return array_shift($this->ppap); 
    }

    public function key()
    {
    }

    public function next()
    {
    }

    public function rewind()
    {
        $this->ppap = [
            'ペン',
            'パイナッポー',
            'アッポー',
            'ペーン',
        ];
    }

    public function valid()
    {
        return count($this->ppap);
    }
}

$ppap = new PPAP();
loop:
$result = '';
foreach ($ppap as $p) {
    $result .= $p;
}
echo $result . PHP_EOL;
if ($result !== 'ペンパイナッポーアッポーペーン') {
    $ppap->rewind();
    goto loop;
}
echo '\(^o^)/ピコ!' . PHP_EOL;

generator

<?php
$result = '';
foreach ((function () {
    $ppap = [
        'ペン',
        'パイナッポー',
        'アッポー',
        'ペーン',
    ];
    shuffle($ppap);

    foreach ($ppap as $p) {
        yield $p;
    }
})() as $p) {
    $result .= $p;
}

echo $result . PHP_EOL;
if ($result !== 'ペンパイナッポーアッポーペーン') {
    require __FILE__;
} else {
    echo '\(^o^)/ピコ!' . PHP_EOL;
}

generator (意地でもshuffle使いたくなかった版)

#!/usr/local/bin/php
<?php
$result = '';
foreach ((function () {
    $ppap = [
        'ペン',
        'パイナッポー',
        'アッポー',
        'ペーン',
    ];

    $f = function ($ppap) {
        $rand = array_rand($ppap);
        $p = $ppap[$rand];
        unset($ppap[$rand]);
        $ppap = array_values($ppap);
        return [$p, $ppap];
    };

    $count = count($ppap);  
    for ($i = 0;$i < $count;$i++) {
        list($p, $ppap) = $f($ppap);
        yield $p;
    }
})() as $p) {
    $result .= $p;
}

echo $result . PHP_EOL;
if ($result !== 'ペンパイナッポーアッポーペーン') {
    system(__FILE__);
} else {
    echo '\(^o^)/ピコ!' . PHP_EOL;
}
9
8
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
9
8

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?