function pairOfDoubles($str) { $letters = str_split($str); foreach ($letters as $i => $letter) { $strOfTwo = $letter . $letters[$i + 1]; $remainder = substr($str, $i + 2); if (strpos($remainder, $strOfTwo) !== false) { return true; } } return false; } //repeating letters with another letter between function repeatSandwich($str) { $letters = str_split($str); foreach ($letters as $i => $letter) { if (isset($letters[$i + 2]) && $letters[$i + 2] === $letter) { return true; } } return false; } $countOfNice = 0; foreach ($strings as $string) { if (isNice($string)) { $countOfNice++; } } echo $countOfNice; return $countOfNice;
function processList($list) { $bits = explode("\n", $list); $nice = 0; foreach ($bits as $str) { if (isNice($str)) { $nice++; } } echo "Nice is {$nice}\n"; }
<?php /** * Check if a string is naughty or nice * * @param string $string * @return bool */ function isNice($string) { return preg_match('/([a-z]{2}).*?(\\1)/i', $string) && preg_match('/([a-z])[a-z](\\1)/i', $string); // has repeating letters } $handle = fopen("input.txt", "r"); $niceStrings = 0; if ($handle) { while (($line = fgets($handle)) !== false) { if (isNice($line)) { $niceStrings++; } } fclose($handle); } echo 'Total nice strings: ' . $niceStrings . PHP_EOL;
<?php $niceStringCount = 0; $input = fopen(__DIR__ . '/input', 'r'); while ($line = fgets($input)) { $niceStringCount += (int) isNice($line); } fclose($input); echo "Number of nice strings: {$niceStringCount}\n";
<?php $input = file_get_contents("inputs/day5input.txt"); $i = 0; foreach (explode("\n", $input) as $string) { // Swap isNice to is2Nice for Part 2 if (isNice(strtolower($string))) { $i = $i + 1; } } echo $i; // Part 1 helping functions function isNice($string) { return hasRepeatLetters($string) && !hasExceptionStrings($string) && hasThreeVowels($string); } function hasRepeatLetters($string) { // Simple back reference should work here // Not sure why the back reference needed escaping though return preg_match("/([a-z])\\1/i", $string); } // This could have been done with a single regex string. Strpos is faster. // I imagined Part 2 would have built on this so I made it easier to adapt. // preg_match("/(ab|cd|pq|xy/", $string) would have been better. function hasExceptionStrings($string) { $strings = ['ab', 'cd', 'pq', 'xy']; foreach ($strings as $str) { // This is faster than a preg_match if (strpos($string, $str) !== false) {