47 lines
1.2 KiB
PHP
47 lines
1.2 KiB
PHP
<?php
|
|
$input_file = '../inputs/day2.txt';
|
|
if (file_exists($input_file)) {
|
|
$input = file_get_contents($input_file);
|
|
if ($input != null) {
|
|
$passwords = explode("\n", $input);
|
|
print 'Part 1 answer: ' . solve_part_one($passwords) . "\n";
|
|
print 'Part 2 answer: ' . solve_part_two($passwords) . "\n";
|
|
}
|
|
}
|
|
|
|
function solve_part_one(array $passwords): int
|
|
{
|
|
function solve_1(int $min, int $max, string $key, string $pass): int
|
|
{
|
|
$letters = array_count_values(str_split($pass));
|
|
if (array_key_exists($key, $letters) && $letters[$key] >= $min && $letters[$key] <= $max)
|
|
return 1;
|
|
return 0;
|
|
}
|
|
|
|
return parse_passwords_and_solve($passwords, 'solve_1');
|
|
}
|
|
|
|
function solve_part_two(array $passwords): int
|
|
{
|
|
function solve_2(int $pos1, int $pos2, string $key, string $pass): int
|
|
{
|
|
if ($pass[$pos1 - 1] === $key xor $pass[$pos2 - 1] === $key)
|
|
return 1;
|
|
return 0;
|
|
}
|
|
|
|
return parse_passwords_and_solve($passwords, 'solve_2');
|
|
}
|
|
|
|
function parse_passwords_and_solve(array $passwords, callable $fun): int
|
|
{
|
|
$ret = 0;
|
|
foreach ($passwords as $policy) {
|
|
preg_match('/^(\d+?)-(\d+?) ([a-z]): (.+?)$/', $policy, $matches);
|
|
[$match, $min, $max, $key, $pass] = $matches;
|
|
if ($match)
|
|
$ret += $fun($min, $max, $key, $pass);
|
|
}
|
|
return $ret;
|
|
}
|