Day 03

 avatar
unknown
php
5 months ago
1.2 kB
32
Indexable
<body style="margin-left: 10px; font-family: consolas; font-size: 18px">

<?php
$day = 3;
$file = "advent$day.txt";
echo "-- Start processing $file --<br><br>";

$input = file_get_contents($file);
// $inputArray = explode("\r\n", $input);

$count = 0;

$donts = explode("don't()", $input);
$dos = array();

// start instructions as do()
array_push($dos, $donts[0]);

$dontsCount = count($donts);

// first dont is [1]
// get substring of donts[1-n] after "do()" if it exists.
for ($i = 1; $i < $dontsCount; $i ++) {

    $do = strstr($donts[$i], "do()");
    if ($do != false)
        array_push($dos, $do);
}

foreach ($dos as $line) {

    $mulPattern = "/mul\(\d{1,3},\d{1,3}\)/";

    preg_match_all($mulPattern, $line, $mulResults);

    for ($i = 0; $i < count($mulResults[0]); $i ++) {

        $mulResult = $mulResults[0][$i];
        echo "Matched text = $mulResult<br>";

        $numPattern = "/\d{1,3}/";
        preg_match_all($numPattern, $mulResult, $nums);
        $num1 = $nums[0][0];
        $num2 = $nums[0][1];
        $prod = $num1 * $num2;
        $count = $count + $prod;
    }
}

echo "<br>Sum: $count";

echo "<br><br>-- Finished processing $file --<br>";
Editor is loading...
Leave a Comment