14th day both parts
This commit is contained in:
22
14/part1.php
Normal file
22
14/part1.php
Normal 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
39
14/part2.php
Normal 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
|
||||
Reference in New Issue
Block a user