Answer ⏱
[VISUALISATION]
Part 1 :
Part 2 :
class Game extends Intcode
{
/**
* Output a value
*
* @param int $value
* @return void
*/
public function sendOutput($value)
{
$last = $this->output->last();
// Add to last group of 3
if ($last && count($last) < 3) {
$this->output[$this->output->count() - 1][] = $value;
return;
}
// Start new group
$this->output[] = [$value];
}
/**
* Get an input
*
* @return int
*/
public function getInput()
{
// Get the ball & paddle positions
foreach ($this->output as $pos) {
if ($pos[2] == 3) $paddle = $pos;
if ($pos[2] == 4) $ball = $pos;
}
// Move the paddle to be under the ball (-1, 0, 1)
return $ball[0] <=> $paddle[0];
}
}
// ==================================================
// > PART 1
// ==================================================
$game_1 = (new Game($input)); $game_1->run();
$solution_1 = $game_1->output->column(2)->keep([2])->count();
// ==================================================
// > PART 2
// ==================================================
$memory = $input->numbers; $memory[0] = 2;
$game_2 = (new Game($memory)); $game_2->run();
// Find last score at position -1, 0
foreach ($game_2->output->reverse() as $pos) {
if ($pos[0] == -1 && $pos[1] == 0) {
$solution_2 = $pos[2];
break;
}
}