14th day both parts

This commit is contained in:
kplaczek
2021-12-14 23:14:43 +01:00
parent 6d58a73344
commit e3494e234a
3 changed files with 67 additions and 1 deletions

22
14/part1.php Normal file
View File

@@ -0,0 +1,22 @@
<?php
$input = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$template = array_shift($input);
$pairs = [];
foreach ($input as $item) {
$line = explode(' -> ', $item);
$pairs[$line[0]] = $line[1];
}
$newTemplate = $template;
for ($j = 0; $j < 10; $j++) {
$tmpTemplate = $newTemplate;
for ($i = 0; $i < strlen($tmpTemplate) - 1; $i++) {
$window = substr($tmpTemplate, $i, 2);
$newTemplate = substr_replace($newTemplate, $pairs[$window], $i + 1 + $i, 0);
}
}
$characters = array_count_values(str_split(($newTemplate)));
sort($characters);
echo array_pop($characters) - array_shift($characters); //2549

39
14/part2.php Normal file
View File

@@ -0,0 +1,39 @@
<?php
$lines = file('input', FILE_IGNORE_NEW_LINES | FILE_SKIP_EMPTY_LINES);
$mapings = [];
$before = [];
$initialMappings = [];
$template = array_shift($lines);
for ($i = 0; $i < strlen($template) - 1; $i++) {
$pair = substr($template, $i, 2);
$before[$pair] = 1;
}
foreach ($lines as $item) {
$line = explode(' -> ', $item);
$mapings[$line[0]] = $line[1];
$initialMappings[$line[0]] = 0;
}
for ($step = 1; $step <= 40; $step++) {
$after = $initialMappings;
foreach ($before as $pair => $count) {
$left = $pair[0] . $mapings[$pair];
$right = $mapings[$pair] . $pair[1];
$after[$left] += $count;
$after[$right] += $count;
}
$before = $after;
}
$letters = [];
foreach ($before as $pair => $count) {
$left = $pair[0];
if (!isset($letters[$left])) {
$letters[$left] = 0;
}
$letters[$left] += $count;
}
$letters[substr($template, -1)] += 1;
sort($letters);
echo array_pop($letters) - array_shift($letters); //2516901104210

View File

@@ -63,4 +63,9 @@
### DAY 13 - Folding paper
- [part1](13/part1.php)
- [part2](13/part2.php)
- [part2](13/part2.php)
### DAY 14 - Polymeric lanternfish
- [part1](14/part1.php)
- [part2](14/part2.php)