Guest User

Untitled

a guest
Dec 18th, 2021
72
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 2.10 KB | None | 0 0
  1. $coords = [];
  2. preg_match('/x=(-?\d+)..(-?\d+), y=(-?\d+)..(-?\d+)/', file_get_contents('input.txt'), $coords);
  3.  
  4. $tx = [$coords[1], $coords[2]];
  5. $ty = [$coords[3], $coords[4]];
  6. sort($tx);
  7. rsort($ty);
  8.  
  9. // the velocity evolution is basically a nth triangle, so anything under that will never reach the target on x direction
  10. $nthTriangle = fn ($i) => $i * ($i + 1) / 2;
  11.  
  12. if ($tx[0] < 0 && $tx[1] > 0) {
  13.     // if target x0 is negative and x1 is positive, scan from x0 to x1
  14.     $xRange = range($tx[0], $tx[1]);
  15. } elseif ($tx[1] <= 0) {
  16.     // if target x0 and x1 are negative, scan from 1st nth triangle < x0, to x1
  17.     $x = 0;
  18.     while (true) {
  19.         $projectedX = $nthTriangle($x);
  20.         if (ceil($projectedX) >= $tx[0] && floor($projectedX) <= $tx[1]) {
  21.             break;
  22.         }
  23.         $x--;
  24.     }
  25.     $xRange = range($tx[0], $x);
  26.     rsort($tx); // swap x0 and x1 in order to make an absolute comparison later
  27. } else {
  28.     // if target x0 and x1 are positive, scan from 1st nth triangle > x0, to x1
  29.     $x = 0;
  30.     while (true) {
  31.         $projectedX = $nthTriangle($x);
  32.         if (ceil($projectedX) >= $tx[0] && floor($projectedX) <= $tx[1]) {
  33.             break;
  34.         }
  35.         $x++;
  36.     }
  37.     $xRange = range($x, $tx[1]);
  38. }
  39.  
  40. $heights = [];
  41. foreach($xRange as $vX) {
  42.     $vY = -abs($ty[1]);
  43.     while ($vY < abs($ty[1])) {
  44.         $probe = ['vX' => $vX, 'vY' => $vY, 'x' => 0, 'y' => 0];
  45.         $height = 0;
  46.         while (true) {
  47.             $probe['x'] += $probe['vX'];
  48.             $probe['y'] += $probe['vY'];
  49.             if ($probe['vX'] !== 0) $probe['vX'] += (($probe['vX'] > 0) ? -1 : 1);
  50.             $probe['vY']--;
  51.             $height = max($height, $probe['y']);
  52.             if ($probe['y'] < $ty[1] || $probe['x'] > abs($tx[1])) {
  53.                 break;
  54.             }
  55.             if ($probe['y'] <= $ty[0] && $probe['x'] >= abs($tx[0])) {
  56.                 $heights[$vY . '_' . $vX] = $height;
  57.                 break;
  58.             }
  59.         }
  60.         $vY++;
  61.     }
  62. }
  63. arsort($heights);
  64. echo 'Part 1: ' . reset($heights).PHP_EOL;
  65. echo 'Part 2: ' . count($heights);
Advertisement
Add Comment
Please, Sign In to add comment