Advent of Code: 2015 – Day 02

Part 1

Problem: Calculate the surface area of a list of boxes, including slack (the area of the smallest side).

Solution: Read in each line of the input file and split using ‘x’ to get the length, width and height. Calculate the size of each unique surface and find the minimum of these (the slack), then calculate the sum of the surfaces twice (since each surface has a mirror image on the opposite side) and the slack.

<?php

declare(strict_types=1);
error_reporting(E_ALL);

$fp = fopen('input', 'r');

$paper_order = 0;

while (($line = fgets($fp)) !== false)
{
    // fgets includes the trailing line break, so remove it
    $line = trim($line);
    list($length, $width, $height) = explode('x', $line);

    $side_areas = [
        $length * $width,
        $width * $height,
        $height * $length
    ];

    $slack = min($side_areas);

    // Each side is repeated twice
    $paper_order += array_sum($side_areas) * 2;
    $paper_order += $slack;
}

fclose($fp);

print("The elves should order this many square feet of wrapping paper: $paper_order\n");

Part 2

Problem: Calculate the length of ribbon required, defined as the volume of the box and the side with the shortest perimeter.

Solution: As per the previous part, read in each line of the file and split to get the dimensions. Calculate the perimeter of each side, then add the minimum perimeter to the volume of the box.

<?php

declare(strict_types=1);
error_reporting(E_ALL);

$fp = fopen('input', 'r');

$ribbon_order = 0;

while (($line = fgets($fp)) !== false)
{
    // fgets includes the trailing line break, so remove it
    $line = trim($line);
    list($length, $width, $height) = explode('x', $line);

    $side_perimeters = array_map(function($x) { return $x * 2; }, [
        $length + $width,
        $width + $height,
        $height + $length
    ]);

    $perimeter_ribbon = min($side_perimeters);
    $volume_ribbon = $length * $width * $height;

    $ribbon_order += $perimeter_ribbon;
    $ribbon_order += $volume_ribbon;
}

fclose($fp);

print("The elves should order this many feet of ribbon: $ribbon_order\n");

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.