Invert FizzBuzz by JimmyZ

<?php
class InverseFizzBuzz {
  public $list;
    public $fblist;

    public function __construct($list) {
        $this->list = $list;
        $this->fb = implode('', $this->_getFBList(0, 200));
    }

    public function sequence() {
        $fb = '/' . implode('\s*', array_map(function ($str) {
                if ( $str == 'FizzBuzz' )    return 'G';
                else if ( $str == 'Fizz' )   return 'F';
                else if ( $str == 'Buzz' )   return 'B';
                else                         return ' ';
            }, $this->list)) . '/';

        preg_match_all($fb, $this->fb, $matches, PREG_OFFSET_CAPTURE | PREG_SET_ORDER);

        $this->_min($matches);
    }

    private function _getFBList($start, $end) {
        return array_map(function ($n) {
                if ( $n == 0 )         return ' ';
                if ( $n % 15 == 0 )    return 'G';
                else if ( $n % 3 == 0) return 'F';
                else if ( $n % 5 == 0) return 'B';
                else                   return ' ';
            }, range($start, $end));
    }

    private function _min($sequences) {
        if (count($sequences) == 0) {
            echo "\n";
            return;
        }

        $sequence = $sequences[0][0];
        $n = strlen($sequences[0][0][0]);
        array_shift($sequences);

        foreach ($sequences as $_sequence) {
            if (($i = strlen($_sequence[0][0])) < $n) {
                $sequence = $_sequence[0];
                $n = $i;
            }
        }

        echo $sequence[1], ' ', strlen($sequence[0]) + $sequence[1] - 1, "\n";
    }
}
while($line = trim(fgets(STDIN))) {
    $ifb = new InverseFizzBuzz(explode(' ', $line));
    $ifb->sequence();
    //var_dump($ifb->sequence());
}

?>

Note that non-ascii characters in the above source code will be escaped (such as \x9f).

download

return to the top page