Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- <?php
- $handle = fopen('input.txt', 'r');
- $lines = array();
- while (($line = fgets($handle)) !== false) {
- $lines[] = $line;
- }
- fclose($handle);
- sort($lines);
- $start_minute = 0;
- $guard_id = 0;
- $guards = array();
- foreach ($lines as $line) {
- if (stripos($line, 'guard') !== false) {
- preg_match('/.*?#(\d+).*?/', $line, $gn);
- $guard_id = (int)$gn[1];
- } elseif (stripos($line, 'fall') !== false) {
- preg_match('/.*?:(\d+)/', $line, $minutes);
- $start_minute = (int)$minutes[1];
- } elseif (stripos($line, 'wakes') !== false) {
- preg_match('/.*?:(\d+)/', $line, $minutes);
- $end_minute = (int)$minutes[1];
- if (!isset($guards[$guard_id])) {
- $guards[$guard_id] = array_fill(0, 60, 0);
- }
- $sleep = array_fill($start_minute, $end_minute - $start_minute, 1);
- $sleep += array_fill_keys(range(0, 59), 0);
- ksort($sleep);
- $guards[$guard_id] = array_map(function (...$arrays) {return array_sum($arrays);}, $guards[$guard_id], $sleep);
- }
- }
- //Part 1:
- uasort($guards, function($a, $b){ return array_sum($a)>array_sum($b)?-1:1;});
- $sleepiest_guard = array_keys($guards)[0];
- $best_minute = array_search(max($guards[$sleepiest_guard]), $guards[$sleepiest_guard], true);
- echo 'Part 1:' . PHP_EOL;
- echo 'The sleepiest guard is #' . $sleepiest_guard . ', the minute he slept the most is ' . $best_minute . PHP_EOL;
- echo 'The solution is: ' . ($sleepiest_guard * $best_minute) . PHP_EOL;
- echo PHP_EOL;
- //Part2:
- uasort($guards, function($a, $b){ return max($a)>max($b)?-1:1;});
- $sleepiest_guard = array_keys($guards)[0];
- $best_minute = array_search(max($guards[$sleepiest_guard]), $guards[$sleepiest_guard], true);
- echo 'Part 2:' . PHP_EOL;
- echo 'The sleepiest guard is #' . $sleepiest_guard . ' he slept the most in minute ' . $best_minute . PHP_EOL;
- echo 'The solution is: ' . ($sleepiest_guard * $best_minute) . PHP_EOL;
Advertisement
Add Comment
Please, Sign In to add comment