You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
This repo is archived. You can view files and clone it, but cannot push or open issues/pull-requests.
aoc-racket/day02.rkt

68 lines
2.5 KiB
Racket

9 years ago
#lang scribble/lp2
@(require scribble/manual aoc-racket/helper)
@aoc-title[2]
9 years ago
@defmodule[aoc-racket/day02]
9 years ago
9 years ago
@link["http://adventofcode.com/day/2"]{The puzzle}. Our @link-rp["day02-input.txt"]{input} is a list of strings that represent dimensions of rectangular boxes.
9 years ago
9 years ago
@chunk[<day02>
<day02-setup>
<day02-q1>
<day02-test>]
9 years ago
@section{How much paper is needed to wrap the boxes?}
According to the problem, the paper needed to wrap a present is the surface area of the box (= the sum of the areas of the sides) plus the area of the smallest side.
9 years ago
First we need to parse our input file into a list of box dimensions. We'll model each box as a list of three dimensions. (The question doesn't need us to keep height / width / depth straight, so we won't worry about it.)
Then we have a traditional setup for the devastating one-two punch of @racket[map] and @racket[apply]. We'll write a function to compute surface area from box dimensions. Then we'll @racket[map] that function across the list of boxes, and finally @racket[apply] the @racket[+] operator to our list of results to get the answer.
9 years ago
9 years ago
@chunk[<day02-setup>
9 years ago
(require racket rackunit)
9 years ago
(provide (all-defined-out))
9 years ago
(define (string->boxes str)
(for/list ([ln (in-list (string-split str "\n"))])
(map string->number (string-split ln "x"))))]
9 years ago
@chunk[<day02-q1>
9 years ago
(define (box->paper box)
(match-define (list x y z) box)
(define sides (list (* x y) (* y z) (* x z)))
(+ (* 2 (apply + sides)) (apply min sides)))
(define (q1 str)
(define boxes (string->boxes str))
(apply + (map box->paper boxes)))]
@section{How much ribbon is needed to wrap the boxes?}
According to the problem, the ribbon needed is the perimeter of the smallest side plus the volume of the box.
We take the same approach, with a new @racket[box->ribbon] function.
9 years ago
@chunk[<day02-q1>
9 years ago
(define (box->ribbon box)
(match-define (list x y z) box)
(define (perimeter dim1 dim2) (* 2 (+ dim1 dim2)))
(define perimeters
(list (perimeter x y) (perimeter y z) (perimeter x z)))
(+ (apply min perimeters) (* x y z)))
(define (q2 str)
(define boxes (string->boxes str))
(apply + (map box->ribbon boxes)))]
9 years ago
@section{Testing Day 2}
9 years ago
9 years ago
@chunk[<day02-test>
9 years ago
(module+ test
9 years ago
(define input-str (file->string "day02-input.txt"))
9 years ago
(check-equal? (q1 input-str) 1586300)
(check-equal? (q2 input-str) 3737498))]