advent_of_code_2019/day_4/part_2.php

63 lines
1.3 KiB
PHP
Raw Permalink Normal View History

2019-12-06 14:32:52 +01:00
<?php
[$min, $max] = explode('-', file_get_contents('input.txt'));
/**
* @param int|string $big_number
*
* @return bool
*/
function has_no_more_than_two_adjacent_number($big_number)
{
$big_number = (string) $big_number;
$current_numbers = [];
for ($i = 0, $l = strlen($big_number); $i < $l; $i++) {
if (!in_array($big_number[$i], $current_numbers, true)) {
if (count($current_numbers) === 2) {
return true;
}
$current_numbers = [$big_number[$i]];
} else {
$current_numbers[] = $big_number[$i];
}
}
return count($current_numbers) === 2;
}
/**
* @param int|string $big_number
* @return bool
*/
function never_decrease($big_number)
{
$big_number = (string) $big_number;
$current_number = null;
for ($i = 0, $l = strlen($big_number); $i < $l; $i++) {
if ($current_number > $big_number[$i]) {
return false;
}
$current_number = $big_number[$i];
}
return true;
}
/**
* @param int|string $number
*
* @return bool
*/
function is_valid($number)
{
return has_no_more_than_two_adjacent_number($number) && never_decrease($number);
}
$valids = [];
for ($i = $min; $i <= $max; $i++) {
if (is_valid($i)) {
$valids[] = $i;
}
}
echo count($valids); // more than 574 & less than 1099