Exemplo n.º 1
1
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;
Exemplo n.º 2
0
function processList($list)
{
    $bits = explode("\n", $list);
    $nice = 0;
    foreach ($bits as $str) {
        if (isNice($str)) {
            $nice++;
        }
    }
    echo "Nice is {$nice}\n";
}
Exemplo n.º 3
0
<?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;
Exemplo n.º 4
0
<?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";
Exemplo n.º 5
0
<?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) {