[2017-12-03] Solutions for both puzzles

master
Elis Hirwing 5 years ago
parent 1c0eecacf5
commit 2971f6c52f
Signed by: etu
GPG Key ID: D57EFA625C9A925F
  1. 2
      Makefile
  2. 116
      day3/main.php

@ -7,6 +7,8 @@ day2:
php day2/main.php
day3:
php day3/main.php
day4:
day5:
day6:

@ -0,0 +1,116 @@
<?php
// https://adventofcode.com/2017/day/3
/*
* Working solution for 2017-12-03 part 1
*/
function puzzle1(int $maxNumber) : int
{
$x = 0;
$y = 0;
$steps = 0;
$diameter = 1;
$direction = 4;
for ($number = 1; $number < $maxNumber; $number++) {
if ($direction === 4) {
$x++;
$diameter += 2;
$direction = 0;
$steps = $diameter - 2;
} else {
switch ($direction) {
case 0:
$y--;
break;
case 1:
$x--;
break;
case 2:
$y++;
break;
case 3:
$x++;
break;
}
$steps--;
if ($steps === 0) {
$direction++;
$steps = $diameter - 1;
}
}
}
return abs($x) + abs($y);
}
/*
* Working solution for 2017-12-03 part 2
*/
function puzzle2(int $maxNumber) : int
{
$x = 0;
$y = 0;
$steps = 0;
$diameter = 1;
$direction = 4;
$map = [];
for ($number = 1; $number < $maxNumber; $number++) {
// x-1,y-1 x,y-1 x+1,y-1
// x-1,y x+1,y+1
// x-1,y+1 x,y+1 x+1,y+1
$newNumber =
($map[$y-1][$x-1] ?? 0) +
($map[$y-1][$x] ?? 0) +
($map[$y-1][$x+1] ?? 0) +
($map[$y][$x-1] ?? 0) +
($map[$y][$x+1] ?? 0) +
($map[$y+1][$x-1] ?? 0) +
($map[$y+1][$x] ?? 0) +
($map[$y+1][$x+1] ?? 0);
$number = ($newNumber === 0) ? 1 : $newNumber;
$map[$y][$x] = $number;
if ($direction === 4) {
$x++;
$diameter += 2;
$direction = 0;
$steps = $diameter - 2;
} else {
switch ($direction) {
case 0:
$y--;
break;
case 1:
$x--;
break;
case 2:
$y++;
break;
case 3:
$x++;
break;
}
$steps--;
if ($steps === 0) {
$direction++;
$steps = $diameter - 1;
}
}
}
return $number - 1;
}
Loading…
Cancel
Save