1
0
Fork 0
advent-of-code/2020/day6.php

44 lines
1.3 KiB
PHP

<?php
$input_file = '../inputs/day6.txt';
if (file_exists($input_file)) {
$input = file_get_contents($input_file);
if ($input != null) {
$answer_groups = explode("\n", $input);
print 'Part 1 answer: ' . solve_part_one($answer_groups) . "\n";
print 'Part 2 answer: ' . solve_part_two($answer_groups) . "\n";
}
}
function solve_part_one(array $answer_groups): int
{
$solve_1 = fn ($form) => strlen(implode('', array_unique(str_split(implode('', $form)))));
return parse_declaration_forms_and_solve($answer_groups, $solve_1);
}
function solve_part_two(array $answer_groups): int
{
$solve_2 = fn ($form) => count(call_user_func_array('array_intersect', array_map(fn ($str) => str_split($str), $form)));
return parse_declaration_forms_and_solve($answer_groups, $solve_2);
}
function parse_declaration_forms_and_solve(array $answer_groups, callable $fn): int
{
$current_answers = [];
$ret = 0;
for ($i = 0; $i < count($answer_groups); $i++) {
$answer = trim($answer_groups[$i]);
if ($answer == '') {
$ret += $fn(array_map(fn ($val) => trim($val), $current_answers));
$current_answers = [];
} else
$current_answers[] = $answer;
}
if (count($current_answers) != 0)
$ret += $fn(array_map(fn ($val) => trim($val), $current_answers));
return $ret;
}