Guest User

Untitled

a guest
Dec 20th, 2018
69
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.17 KB | None | 0 0
  1. <?php
  2. $input = str_split(file_get_contents('input.txt'));
  3.  
  4. $x = 100;
  5. $y = 100;
  6.  
  7. $ymax = $y * 2;
  8.  
  9. $current = $previous = $x + $y * $ymax;
  10.  
  11. $dists = array_fill(0, $current * 2, 0);
  12.  
  13. $pos = array();
  14. $directions = array('N' => -$ymax, 'S' => $ymax, 'W' => -1, 'E' => 1);
  15.  
  16. array_shift($input); //Remove ^
  17. array_pop($input); //Remove $
  18.  
  19. foreach ($input as $i) {
  20.     switch ($i) {
  21.         case '|':
  22.             $p = end($pos);
  23.             $current = $p;
  24.             break;
  25.         case '(':
  26.             $pos[] = $current;
  27.             break;
  28.         case ')':
  29.             $p = array_pop($pos);
  30.             $current = $p;
  31.             break;
  32.         default:
  33.             $dir = $directions[$i];
  34.             $current += $dir;
  35.  
  36.             $dc = $dists[$current];
  37.             $dp = $dists[$previous];
  38.  
  39.             if ($dc === 0) {
  40.                 $dists[$current] = $dp + 1;
  41.             } else {
  42.                 $dists[$current] = $dc > $dp ? $dp + 1 : $dc;
  43.             }
  44.     }
  45.     $previous = $current;
  46. }
  47.  
  48. printf('Part 1: %d', max($dists));
  49. echo PHP_EOL;
  50. printf('Part 2: %d', count(array_filter($dists, function ($n) {
  51.     return $n >= 1000;
  52. })));
  53. echo PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment