Skip to content

Instantly share code, notes, and snippets.

@ounziw
Last active June 21, 2019 09:37
Show Gist options
  • Save ounziw/f98db3db23222e1aa8f876cb23462285 to your computer and use it in GitHub Desktop.
Save ounziw/f98db3db23222e1aa8f876cb23462285 to your computer and use it in GitHub Desktop.
<?php
declare(strict_types=1);
namespace Nagoyaphp\Dokaku16;
class Dokaku16
{
public $ok;
public $numbers;
public $height;
public $width;
public function run(string $input) : string
{
$this->setNumbers($input);
for ($i=0;$i<$this->width*$this->height;$i++) {
$this->findRoutes();
}
return $this->getResults();
}
public function getResults() {
$output = '';
for ($i=0;$i<$this->width*$this->height;$i++) {
$output .= $this->returnAsteriskOrNumber($i);
if ($i % $this->width == $this->width -1) { // 行の最後に / を入れる
$output .= '/';
}
}
$output = trim($output, '/'); // 一番最後の / は削る
return $output;
}
public function returnAsteriskOrNumber($position) {
if ($this->ok[$position]) {
return '*';
} else {
return $this->numbers[$position];
}
}
public function setNumbers($input) {
// 幅は、入力の最初の / の位置
$this->width = strpos($input, '/');
// 高さは、/ の数 +1
$this->height = 1 + substr_count($input, '/');
$input = str_replace('/', '', $input);
$this->numbers = str_split($input);
$this->ok = [];
for ($i=0;$i<$this->width*$this->height;$i++) {
$this->ok[] = 0;
$this->ok[2] = 1; // 中央の上は3番目
}
}
public function findRoutes() {
for ($i=0;$i<$this->width*$this->height;$i++) {
$adjacents = [];
if ($i % $this->width != 0) { // left
$adjacents[] = $i-1;
}
if ($i % $this->width != $this->width-1) { // right
$adjacents[] = $i+1;
}
if ($i >= $this->height) { // up
$adjacents[] = $i - $this->height;
}
if ($i < ($this->width -1) * $this->height) { // down
$adjacents[] = $i + $this->height;
}
foreach ($adjacents as $adjacent) {
$this->checkOk($i,$adjacent);
}
}
}
public function checkOk($val1, $val2) {
if ($this->isOk($val2) && $this->diff($val1, $val2)) {
$this->ok[$val1] = 1;
}
}
public function isOk($val) {
return $this->ok[$val];
}
public function diff($val1, $val2) {
if ($this->numbers[$val1] == $this->numbers[$val2]) {
return true;
} elseif($this->numbers[$val1] == (1 + $this->numbers[$val2])) {
return true;
} elseif ($this->numbers[$val1] == (-1 + $this->numbers[$val2])) {
return true;
} else {
return false;
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment