✨ Add day 10 part 1
This commit is contained in:
parent
20e2c5c324
commit
51860c5116
44
day_10/functions.php
Normal file
44
day_10/functions.php
Normal file
@ -0,0 +1,44 @@
|
||||
<?php
|
||||
|
||||
|
||||
/**
|
||||
* @param array $array
|
||||
* @return array|bool
|
||||
*/
|
||||
function array_flatten(array $array) {
|
||||
return iterator_to_array(array_flatten_iterator($array), false);
|
||||
}
|
||||
|
||||
/**
|
||||
* @param array $array
|
||||
* @return Generator
|
||||
*/
|
||||
function array_flatten_iterator(array $array) {
|
||||
foreach ($array as $value) {
|
||||
if (is_array($value)) {
|
||||
yield from array_flatten_iterator($value);
|
||||
} else {
|
||||
yield $value;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
/**
|
||||
* @param int $x1
|
||||
* @param int $y1
|
||||
* @param int $x2
|
||||
* @param int $y2
|
||||
*
|
||||
* @return array
|
||||
*/
|
||||
function getPointsBetween(int $x1, int $y1, int $x2, int $y2)
|
||||
{
|
||||
$dx = $x2-$x1;
|
||||
$dy = $y2-$y1;
|
||||
$max = max(abs($dx), abs($dy));
|
||||
for($t = 0; $t<=$max; $t++) {
|
||||
$points[] = sprintf('%s,%s', $x1+($t*$dx)/$max, $y1+($t*$dy)/$max);
|
||||
}
|
||||
|
||||
return $points;
|
||||
}
|
54
day_10/part_1.php
Normal file
54
day_10/part_1.php
Normal file
@ -0,0 +1,54 @@
|
||||
<?php
|
||||
|
||||
include 'functions.php';
|
||||
|
||||
$rows = explode("\n", file_get_contents('input.txt'));
|
||||
|
||||
// Make the list of asteroids coordinates
|
||||
$asteroids = array_flatten(
|
||||
array_filter(
|
||||
array_map(static function($row, $i) {
|
||||
return array_filter(array_map(static function($col, $j) use ($i) {
|
||||
if ($col === '#') {
|
||||
return sprintf('%s,%s', $i, $j);
|
||||
}
|
||||
|
||||
return null;
|
||||
}, str_split($row), range(0, strlen($row))));
|
||||
}, $rows, range(0, count($rows)))
|
||||
)
|
||||
);
|
||||
|
||||
$asteroid_count = [];
|
||||
foreach ($asteroids as $asteroid_base) {
|
||||
$count = 0;
|
||||
foreach ($asteroids as $asteroid_target) {
|
||||
if ($asteroid_base === $asteroid_target) {
|
||||
continue;
|
||||
}
|
||||
|
||||
$points_base = explode(',', $asteroid_base);
|
||||
$points_target = explode(',', $asteroid_target);
|
||||
|
||||
$points = getPointsBetween($points_base[0], $points_base[1], $points_target[0], $points_target[1]);
|
||||
|
||||
$add_point = true;
|
||||
foreach ($points as $point) {
|
||||
if ($point === $asteroid_base || $point === $asteroid_target) {
|
||||
continue;
|
||||
}
|
||||
if (in_array($point, $asteroids)) {
|
||||
$add_point = false;
|
||||
break;
|
||||
}
|
||||
}
|
||||
if ($add_point) {
|
||||
$count++;
|
||||
}
|
||||
}
|
||||
$asteroid_count[$asteroid_base] = $count;
|
||||
}
|
||||
|
||||
arsort($asteroid_count);
|
||||
var_dump($asteroid_count);
|
||||
echo current($asteroid_count);
|
Loading…
Reference in New Issue
Block a user