From ec95bf332c5b01b0569e8fa6e82d9937c99354dd Mon Sep 17 00:00:00 2001 From: Clement Desmidt Date: Wed, 15 Dec 2021 12:37:46 +0100 Subject: [PATCH] :sparkles: Ajoute le jour 14 --- day_14/part_1.php | 30 ++++++++++++++++++++++++++ day_14/part_2.php | 55 +++++++++++++++++++++++++++++++++++++++++++++++ 2 files changed, 85 insertions(+) create mode 100644 day_14/part_1.php create mode 100644 day_14/part_2.php diff --git a/day_14/part_1.php b/day_14/part_1.php new file mode 100644 index 0000000..f806923 --- /dev/null +++ b/day_14/part_1.php @@ -0,0 +1,30 @@ + ', $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); diff --git a/day_14/part_2.php b/day_14/part_2.php new file mode 100644 index 0000000..0e2567b --- /dev/null +++ b/day_14/part_2.php @@ -0,0 +1,55 @@ + ', $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); +