advent_of_code_2019/day_16/part_1.php

65 lines
1.8 KiB
PHP
Raw Normal View History

<?php
function flatten(array $array)
{
$result = [];
foreach ($array as $value) {
$key = current(array_keys($value));
$result[$key] = $value[$key];
}
return $result;
}
function generate_patterns($sequence_length)
{
$base_pattern = [0, 1, 0, -1];
$base_pattern_length = count($base_pattern);
$patterns = [];
for($i = 0; $i <= $sequence_length; $i++) {
$current_pattern = [];
$j = $i + 1;
// $i = 0, pattern = $base_pattern en boucle
// $i = 1, pattern = chaque base pattern * $j (en virant le 1er)
for ($m = 0; $m <= $sequence_length / $base_pattern_length; $m++) {
foreach ($base_pattern as $kValue) {
if (array_key_exists($i, $current_pattern)) {
$current_pattern[$i] .= str_repeat($kValue.',', $j);
} else {
$current_pattern[$i] = str_repeat($kValue.',', $j);
}
}
}
$patterns[] = substr($current_pattern[$i], 2);
}
unset($current_pattern, $i, $j, $m, $k);
return $patterns;
}
$sequence = str_split(file_get_contents('input.txt'));
$sequence_length = count($sequence);
echo "generating patterns…\n";
$patterns = generate_patterns($sequence_length);
echo "patterns generated\n";
for ($loops = 0; $loops < 100; $loops++) {
$numbers = [];
foreach ($sequence as $i => $number) {
$line_pattern = explode(',', $patterns[$i]);
$numbers[] = substr(
array_sum(
array_map(function($number, $pattern) use ($line_pattern) {
return $number * $line_pattern[$pattern];
}, $sequence, range(0, $sequence_length))
), -1
);
}
$sequence = $numbers;
echo "loop $loops finished\n";
}
echo implode('', array_slice($sequence, 0, 8));