class Robot extends Intcode
{
public function __construct($ops, $start)
{
parent::__construct($ops);
$this->grid = new Grid();
$this->grid->set([0, 0], $start);
$this->pos = xy([0, 0]);
$this->dir = 0; // [up, right, down, left]
$this->mode = 0; // [write, move]
}
/**
* Output a value
*
* @param int $value
* @return void
*/
public function sendOutput($value)
{
if ($this->mode) {
// Rotate + Move
$this->dir = Math::mod($this->dir + ((int) $value * 2) - 1, 4);
$this->pos->direction(["up", "right", "down", "left"][$this->dir]);
} else {
// Write
$this->grid->set($this->pos, $value ? 1 : 0);
}
$this->mode = ($this->mode + 1) % 2;
}
/**
* Get an input
*
* @return int
*/
public function getInput()
{
if ($this->grid->get($this->pos)) {
return 1;
} else {
return 0;
}
}
/**
* Return the grid
*
* @return Grid
*/
public function onStop()
{
return $this->grid;
}
}
// ==================================================
// > PART 1
// ==================================================
$solution_1 = (new Robot($input, 0))->run()->cells()->count();
// ==================================================
// > PART 2
// ==================================================
$solution_2 = (new Robot($input, 1))->run()
->fillVoid(" ")->rows->callEach()->join("")->callEach()->replace(["0", "1"], [" ", "#"])->join("<br>");