Add day 8

This commit is contained in:
Clement Desmidt 2019-12-09 11:57:44 +01:00
parent ecf949607b
commit 40e99b8702
3 changed files with 95 additions and 1 deletions

3
.gitignore vendored
View File

@ -1,2 +1,3 @@
input.txt input.txt
/.idea /.idea
/day_8/part_2.png

25
day_8/part_1.php Normal file
View File

@ -0,0 +1,25 @@
<?php
$input = file_get_contents('input.txt');
const WIDTH = 25;
const HEIGHT = 6;
$area = WIDTH * HEIGHT;
$layers = array_map(static function($layer) {
return str_split($layer);
}, str_split($input, $area));
usort($layers, function($layer_a, $layer_b) {
$a0 = array_count_values($layer_a)['0'];
$b0 = array_count_values($layer_b)['0'];
if ($a0 === $b0) {
return 0;
}
return $a0 < $b0 ? -1 : 1 ;
});
reset($layers);
$fewest_0_layer = current($layers);
echo array_count_values($fewest_0_layer)['1'] * array_count_values($fewest_0_layer)['2'];

68
day_8/part_2.php Normal file
View File

@ -0,0 +1,68 @@
<?php
$input = file_get_contents('input.txt');
const TRANSPARENT = 2;
const WHITE = 1;
const BLACK = 0;
const WIDTH = 25;
const HEIGHT = 6;
$area = WIDTH * HEIGHT;
function flatten(array $array) {
$return = [];
array_walk_recursive($array, static function($a) use (&$return) { $return[] = $a; });
return implode('', $return);
}
$layers = array_map(static function($layer) {
return str_split($layer, WIDTH);
}, str_split($input, $area));
$final_image = array_fill(0, HEIGHT, []);
$final_image = array_map(static function() {
return array_fill(0, WIDTH, TRANSPARENT);
}, $final_image);
foreach ($layers as $layer) {
foreach ($layer as $row => $line) {
$numbers = str_split($line);
foreach ($numbers as $col => $number) {
if ($final_image[$row][$col] == TRANSPARENT) {
$final_image[$row][$col] = $number;
}
}
}
}
$image = new Imagick();
$white = new \ImagickPixel('#FFFFFF');
$black = new \ImagickPixel('#000000');
$image->newImage(WIDTH * 10, HEIGHT * 10, 'none');
$image->setImageFormat('png');
$draw = new \ImagickDraw();
foreach ($final_image as $j => $row) {
foreach ($row as $i => $cell) {
$color = 'none';
if ($cell == WHITE) {
$color = $white;
}
if ($cell == BLACK) {
$color = $black;
}
$draw->setFillColor($color);
$draw->rectangle(10 * $i, 10 * $j, 10 * $i + 10, 10 * $j + 10);
}
}
$image->drawImage($draw);
header("Content-Type: image/png");
$data = $image->getImageBlob();
file_put_contents('part_2.png', $data);