advent_of_code_2022

My (attempted) solutions to the 2022 Advent of Code
git clone https://git.eamoncaddigan.net/advent_of_code_2022.git
Log | Files | Refs | README

commit ac59777db333e40d23938c9148d5f0953515dcbc
parent e38ebb7fcfc7a00fba183c1d6b178a0da0bc1fc6
Author: Eamon Caddigan <eamon.caddigan@gmail.com>
Date:   Fri,  9 Dec 2022 14:43:26 -0800

Solution to day 9, part 1.

Diffstat:
Asrc/day_9.jl | 77+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
1 file changed, 77 insertions(+), 0 deletions(-)

diff --git a/src/day_9.jl b/src/day_9.jl @@ -0,0 +1,77 @@ +#!/usr/bin/env julia +# https://adventofcode.com/2022/day/9 +using AdventOfCode + +example = readlines(IOBuffer(""" + R 4 + U 4 + L 3 + D 1 + R 4 + D 1 + L 5 + R 2""")) +input = readlines("data/day_9.txt") + +function increment_head_tail(head_position::Tuple{Int,Int}, + tail_position::Tuple{Int,Int}, + direction::Char) + if direction == 'L' + if head_position[1] - tail_position[1] < 0 + tail_position = head_position + end + head_position = (head_position[1] - 1, head_position[2]) + elseif direction == 'R' + if head_position[1] - tail_position[1] > 0 + tail_position = head_position + end + head_position = (head_position[1] + 1, head_position[2]) + elseif direction == 'D' + if head_position[2] - tail_position[2] < 0 + tail_position = head_position + end + head_position = (head_position[1], head_position[2] - 1) + elseif direction == 'U' + if head_position[2] - tail_position[2] > 0 + tail_position = head_position + end + head_position = (head_position[1], head_position[2] + 1) + else + error("invalid direction") + end + + (head_position, tail_position) +end + +function move_head_tail(instructions) + head_position, tail_position = ((0,0), (0,0)) + tail_visits = Set{Tuple{Int,Int}}() + push!(tail_visits, tail_position) + + for instruction = instructions + direction = instruction[1] + steps = parse(Int, instruction[3:end]) + for _ = 1:steps + head_position, tail_position = increment_head_tail( + head_position, + tail_position, + direction + ) + push!(tail_visits, tail_position) + end + end + + tail_visits +end + +function part_1(input) + length(move_head_tail(input)) +end +@assert part_1(example) == 13 +@info part_1(input) + +function part_2(input) + nothing +end +@assert part_2(example) == nothing +@info part_2(input)