--- Day 3: Perfectly Spherical Houses in a Vacuum ---

Santa is delivering presents to an infinite two-dimensional grid of houses.

He begins by delivering a present to the house at his starting location, and then an elf at the North Pole calls him via radio and tells him where to move next. Moves are always exactly one house to the north (^), south (v), east (>), or west (<). After each move, he delivers another present to the house at his new location.

However, the elf back at the north pole has had a little too much eggnog, and so his directions are a little off, and Santa ends up visiting some houses more than once. How many houses receive at least one present?

For example:

  • > delivers presents to 2 houses: one at the starting location, and one to the east.
  • ^>v< delivers presents to 4 houses in a square, including twice to the house at his starting/ending location.
  • ^v^v^v^v^v delivers a bunch of presents to some very lucky children at only 2 houses.

Rust Solution

use rustgym_util::*;
use std::collections::HashSet;
use std::fmt::Write;
use std::io::*;

pub fn solve(reader: &mut dyn BufRead, writer: &mut dyn Write) {
    let mut it = reader.lines().map(|l| l.unwrap());
    let line = it.next().unwrap();
    let mut x = 0;
    let mut y = 0;
    let mut hs1: HashSet<(i32, i32)> = HashSet::new();
    let mut hs2: HashSet<(i32, i32)> = HashSet::new();
    let mut xs: [i32; 2] = [0, 0];
    let mut ys: [i32; 2] = [0, 0];
    hs1.insert((0, 0));
    hs2.insert((0, 0));
    for (i, c) in line.char_indices() {
        let j = i % 2;
        match c {
            '>' => {
                x += 1;
                xs[j] += 1;
            }
            '<' => {
                x -= 1;
                xs[j] -= 1;
            }
            '^' => {
                y += 1;
                ys[j] += 1;
            }
            'v' => {
                y -= 1;
                ys[j] -= 1;
            }
            _ => {}
        }
        hs1.insert((x, y));
        hs2.insert((xs[j], ys[j]));
    }
    let res1 = hs1.len();
    let res2 = hs2.len();
    writeln!(writer, "{}", res1).unwrap();
    writeln!(writer, "{}", res2).unwrap();
}

advent_of_code!(test, "input.txt", "output.txt");

Having problems with this solution? Click here to submit an issue on github.