$grid = [];
// Build the grid
for ($x = 1; $x <= 300; $x++) {
for ($y = 1; $y <= 300; $y++) {
$power = (($x + 10) * $y + $input->int) * ($x + 10);
$power = (int) $power < 100 ? 0 : substr($power, -3, 1);
$grid[$y][$x] = $power - 5;
}
}
function find_best_square($grid, $size = 3) {
$max_power = 0;
$position = null;
for ($x = 1; $x <= 300 - $size + 1; $x++) {
for ($y = 1; $y <= 300 - $size + 1; $y++) {
$power = 0;
for ($i = 0; $i < $size; $i++) {
for ($j = 0; $j < $size; $j++) {
$power += $grid[$y + $i][$x + $j];
}
}
if ($power > $max_power) {
$max_power = $power;
$position = "$x,$y";
}
}
}
return [$position, $max_power];
}
// ==================================================
// > PART 1
// ==================================================
$solution_1 = find_best_square($grid, 3)[0];
// ==================================================
// > PART 2
// ==================================================
$max_power = 0;
foreach (range(13, 17) as $size) { // Search in predefined range of sizes
$found = find_best_square($grid, $size);
if ($found[1] > $max_power) {
$max_power = $found[1];
$solution_2 = [$found[0] . ",$size", $max_power];
}
}