1
0
Fork 0
Browse Source

TASK: 2018 - Day 5

master
Michael Gerdemann 4 years ago
parent
commit
020c08a913
  1. 99
      2018/5/app.php
  2. 1
      2018/5/input.txt

99
2018/5/app.php

@ -0,0 +1,99 @@
<?php
/*
* Advent of Code - Day 5
*/
// Input
$polymer = trim(file_get_contents('input.txt'));
// Task 1:
/**
* React
*
* @param string $a
* @param string $a
* @return bool
*/
function react(string $a, string $b): bool
{
return (ord($a) !== ord($b) && strtolower($a) === strtolower($b));
}
/**
* Test a polymer
*
* @param string $polymer
* @return string
*/
function testPolymer(string $polymer): string
{
$newPolymer = '';
do {
if (!empty($newPolymer)) {
$polymer = $newPolymer;
}
$units = str_split($polymer, 2);
foreach ($units as $key => $unitCouple) {
$unitCoupleParts = str_split($unitCouple);
if (count($unitCoupleParts) == 2 && react($unitCoupleParts[0], $unitCoupleParts[1])) {
unset($units[$key]);
}
}
$newPolymer = implode('', $units);
} while ($newPolymer != $polymer);
return $polymer;
}
/**
* Get final length of polymer
*
* @param string $polymer
* @return int
*/
function getFinalPolymerLength(string $polymer): int
{
$isFirstChar = true;
$break = false;
do {
if ($isFirstChar === false) {
$firstChar = substr($polymer, 0, 1);
$polymer = substr($polymer, 1);
}
$testedPolymer = testPolymer($polymer);
if ($isFirstChar) {
$isFirstChar = false;
} else {
$polymer = $firstChar . $polymer;
$testedPolymer = $firstChar . $testedPolymer;
$isFirstChar = true;
}
if ($polymer != $testedPolymer) {
$polymer = $testedPolymer;
} else {
$break = true;
}
} while ($break === false);
return strlen($polymer);
}
echo sprintf(
'Result 1: %s%s',
getFinalPolymerLength($polymer),
PHP_EOL
);
// Task 2:
$minCount = strlen($polymer);
foreach (range('a', 'z') as $char) {
$currentCount = getFinalPolymerLength(str_replace($char, '', str_replace(strtoupper($char), '', $polymer)));
if ($currentCount < $minCount) {
$minCount = $currentCount;
}
}
echo sprintf(
'Result 2: %s%s',
$minCount,
PHP_EOL
);

1
2018/5/input.txt

File diff suppressed because one or more lines are too long
Loading…
Cancel
Save