advent_of_code_2021/day_17/part_1.php

58 lines
1.4 KiB
PHP
Raw Normal View History

2021-12-17 10:51:20 +01:00
<?php
$input = file_get_contents('./input.txt');
preg_match('/^target area: x=(\d+)\.\.(\d+), y=(-?\d+)\.\.(-?\d+)$/', $input, $matches);
[, $x_min, $x_max, $y_min, $y_max] = $matches;
$target = ['x_min' => $x_min, 'x_max' => $x_max, 'y_min' => $y_min, 'y_max' => $y_max];
function increment(&$x, &$y, &$x_velocity, &$y_velocity)
{
$current_x = $x;
$x += $x_velocity;
$y += $y_velocity;
if ($x_velocity > 0) $x_velocity -= 1;
elseif ($x_velocity < 0) $x_velocity += 1;
else $x_velocity = 0;
$y_velocity -= 1;
}
function check($x, $y, $target)
{
return $x >= $target['x_min'] &&
$x <= $target['x_max'] &&
$y >= $target['y_min'] &&
$y <= $target['y_max'];
}
$x = 0;
$y = 0;
$x_velocity = 6;
$y_velocity = 9;
$max = 0;
for ($i = 1; $i < abs($target['x_min']); $i++) {
$tmp_max = 0;
for ($j = 1; $j < abs($target['y_min']); $j++) {
$x = 0;
$y = 0;
$x_velocity = $i;
$y_velocity = $j;
$tmp_max = max($tmp_max, $y);
while(!check($x, $y, $target)) {
echo sprintf('x: %s, y: %s%s', $x, $y, "\n");
increment($x, $y, $x_velocity, $y_velocity);
$tmp_max = max($tmp_max, $y);
if ($y <= $target['y_min']) {
break;
}
}
if (check($x, $y, $target)) {
$max = max($max, $tmp_max);
}
}
}
echo $max;