40 lines
1.1 KiB
PHP
40 lines
1.1 KiB
PHP
<?php
|
|
$input_file = '../inputs/day3.txt';
|
|
if (file_exists($input_file)) {
|
|
$input = file_get_contents($input_file);
|
|
if ($input != null) {
|
|
$coordinates = explode("\n", $input);
|
|
print 'Part 1 answer: ' . solve_part_one($coordinates) . "\n";
|
|
print 'Part 2 answer: ' . solve_part_two($coordinates) . "\n";
|
|
}
|
|
}
|
|
|
|
function solve_part_one(array $coords): int
|
|
{
|
|
return solve_for_slope($coords, 3, 1);
|
|
}
|
|
|
|
function solve_part_two(array $coords): int
|
|
{
|
|
return solve_for_slope($coords, 1, 1)
|
|
* solve_for_slope($coords, 3, 1)
|
|
* solve_for_slope($coords, 5, 1)
|
|
* solve_for_slope($coords, 7, 1)
|
|
* solve_for_slope($coords, 1, 2);
|
|
}
|
|
|
|
function solve_for_slope(array $coords, int $incr_x, int $incr_y): int
|
|
{
|
|
$current_coords = ['x' => 0, 'y' => 0];
|
|
$trees = 0;
|
|
while ($current_coords['y'] < (count($coords) - 1)) {
|
|
$current_coords['x'] += $incr_x;
|
|
$current_coords['y'] += $incr_y;
|
|
|
|
$current_line = trim($coords[$current_coords['y']]);
|
|
$actual_x = $current_coords['x'] % strlen($current_line);
|
|
if ($current_line[$actual_x] === '#')
|
|
$trees += 1;
|
|
}
|
|
return $trees;
|
|
}
|