Guest User

Untitled

a guest
Dec 4th, 2018
106
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
PHP 1.95 KB | None | 0 0
  1. <?php
  2. $handle = fopen('input.txt', 'r');
  3. $lines = array();
  4.  
  5. while (($line = fgets($handle)) !== false) {
  6.     $lines[] = $line;
  7. }
  8. fclose($handle);
  9.  
  10. sort($lines);
  11.  
  12. $start_minute = 0;
  13. $guard_id = 0;
  14. $guards = array();
  15.  
  16. foreach ($lines as $line) {
  17.     if (stripos($line, 'guard') !== false) {
  18.         preg_match('/.*?#(\d+).*?/', $line, $gn);
  19.         $guard_id = (int)$gn[1];
  20.     } elseif (stripos($line, 'fall') !== false) {
  21.         preg_match('/.*?:(\d+)/', $line, $minutes);
  22.         $start_minute = (int)$minutes[1];
  23.     } elseif (stripos($line, 'wakes') !== false) {
  24.         preg_match('/.*?:(\d+)/', $line, $minutes);
  25.         $end_minute = (int)$minutes[1];
  26.  
  27.         if (!isset($guards[$guard_id])) {
  28.             $guards[$guard_id] = array_fill(0, 60, 0);
  29.         }
  30.  
  31.         $sleep = array_fill($start_minute, $end_minute - $start_minute, 1);
  32.         $sleep += array_fill_keys(range(0, 59), 0);
  33.  
  34.         ksort($sleep);
  35.  
  36.         $guards[$guard_id] = array_map(function (...$arrays) {return array_sum($arrays);}, $guards[$guard_id], $sleep);
  37.     }
  38. }
  39.  
  40. //Part 1:
  41.  
  42. uasort($guards, function($a, $b){ return array_sum($a)>array_sum($b)?-1:1;});
  43.  
  44. $sleepiest_guard = array_keys($guards)[0];
  45. $best_minute = array_search(max($guards[$sleepiest_guard]), $guards[$sleepiest_guard], true);
  46.  
  47. echo 'Part 1:' . PHP_EOL;
  48. echo 'The sleepiest guard is #' . $sleepiest_guard . ', the minute he slept the most is ' . $best_minute . PHP_EOL;
  49. echo 'The solution is: ' . ($sleepiest_guard * $best_minute) . PHP_EOL;
  50. echo PHP_EOL;
  51.  
  52. //Part2:
  53.  
  54. uasort($guards, function($a, $b){ return max($a)>max($b)?-1:1;});
  55.  
  56. $sleepiest_guard = array_keys($guards)[0];
  57. $best_minute = array_search(max($guards[$sleepiest_guard]), $guards[$sleepiest_guard], true);
  58.  
  59. echo 'Part 2:' . PHP_EOL;
  60. echo 'The sleepiest guard is #' . $sleepiest_guard  . ' he slept the most in minute ' . $best_minute . PHP_EOL;
  61. echo 'The solution is: ' . ($sleepiest_guard * $best_minute) . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment