Ajoute le jour 14

This commit is contained in:
Clement Desmidt 2021-12-15 12:37:46 +01:00
parent 637e029dc1
commit ec95bf332c
2 changed files with 85 additions and 0 deletions

30
day_14/part_1.php Normal file
View File

@ -0,0 +1,30 @@
<?php
[$template, $rules] = explode("\n\n", file_get_contents('./input.txt'));
$template = str_split($template);
$pair_insertion_rules = [];
foreach (explode("\n", $rules) as $rule) {
[$key, $value] = explode(' -> ', $rule);
$pair_insertion_rules[$key] = $value;
}
for ($i = 0; $i < 40; $i++) {
$tmp = [];
foreach ($template as $i_char => $char) {
if (array_key_exists($i_char+1, $template)) {
$tmp[] = $char;
$pair = $char . $template[$i_char + 1];
if (array_key_exists($pair, $pair_insertion_rules)) {
$tmp[] = $pair_insertion_rules[$pair];
}
}
}
$tmp[] = array_pop($template);
$template = $tmp;
echo $i."\n";
}
$count_char = array_count_values($template);
echo max($count_char) - min($count_char);

55
day_14/part_2.php Normal file
View File

@ -0,0 +1,55 @@
<?php
[$template, $rules] = explode("\n\n", file_get_contents('./input.txt'));
$template = str_split($template);
$pair_insertion_rules = [];
foreach (explode("\n", $rules) as $rule) {
[$key, $value] = explode(' -> ', $rule);
$pair_insertion_rules[$key] = $value;
}
$pair_counts = count_pairs($template);
for ($i = 0; $i < 40; $i++) {
$new_pair_counts = $pair_counts;
foreach ($pair_counts as $key => $value) {
$substitute = $pair_insertion_rules[$key];
$pair1 = $key[0] . $substitute;
$pair2 = $substitute . $key[1];
$new_pair_counts[$pair1] = array_key_exists($pair1, $new_pair_counts) ? $new_pair_counts[$pair1] + $value : $value;
$new_pair_counts[$pair2] = array_key_exists($pair2, $new_pair_counts) ? $new_pair_counts[$pair2] + $value : $value;
$new_pair_counts[$key] = $new_pair_counts[$key] - $value;
if ($new_pair_counts[$key] < 1) {
unset($new_pair_counts[$key]);
}
}
$pair_counts = $new_pair_counts;
}
$count_elements = [];
foreach ($pair_counts as $pair => $pair_count) {
foreach (str_split($pair) as $element) {
$count_elements[$element] = array_key_exists($element, $count_elements) ? $count_elements[$element] + $pair_count : $pair_count;
}
}
array_walk($count_elements, static function (&$count_element) {
$count_element = ceil($count_element / 2);
});
function count_pairs($template): array
{
$counts = [];
for ($i = 0; $i < count($template) - 1; $i++) {
$pair = $template[$i] . $template[$i + 1];
$counts[$pair] = array_key_exists($pair, $counts) ? $counts[$pair]+1 : 1;
}
return $counts;
}
echo max($count_elements) - min($count_elements);