summaryrefslogtreecommitdiff
path: root/2022/src/bin/day_9.rs
blob: ccbb66a63988a431855c99fae3e2d33541d7c1ff (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
use nom::{
    branch::alt,
    bytes::complete::tag,
    character::complete::{i32, line_ending},
    combinator::{map, value},
    multi::separated_list1,
    sequence::tuple,
    IResult,
};
use std::{collections::BTreeSet, fs};

fn main() -> Result<(), Box<dyn std::error::Error>> {
    let input = fs::read_to_string("inputs/day_9.txt")?;
    let movements = Movements::parser(&input).unwrap().1;

    let mut game_board_part_1 = GameBoard::new(2);
    for instruction in &movements.0 {
        game_board_part_1.step(instruction);
    }
    dbg!(game_board_part_1.tail_visited.len());

    let mut game_board_part_2 = GameBoard::new(10);
    for instruction in &movements.0 {
        game_board_part_2.step(instruction);
    }
    dbg!(game_board_part_2.tail_visited.len());

    Ok(())
}

#[derive(Debug)]
struct Movements(Vec<Instruction>);

#[derive(Debug)]
struct Instruction {
    direction: Direction,
    distance: i32,
}

#[derive(Debug, Clone, Copy)]
enum Direction {
    Down,
    Up,
    Left,
    Right,
}

impl Movements {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(separated_list1(line_ending, Instruction::parser), Movements)(input)
    }
}

impl Instruction {
    fn parser(input: &str) -> IResult<&str, Self> {
        map(
            tuple((Direction::parser, tag(" "), i32)),
            |(direction, _, distance)| Instruction {
                direction,
                distance,
            },
        )(input)
    }
}

impl Direction {
    fn parser(input: &str) -> IResult<&str, Self> {
        alt((
            value(Direction::Down, tag("D")),
            value(Direction::Up, tag("U")),
            value(Direction::Left, tag("L")),
            value(Direction::Right, tag("R")),
        ))(input)
    }
}

#[derive(Debug)]
struct GameBoard {
    rope: Vec<Position>,
    tail_visited: BTreeSet<Position>,
}

#[derive(Default, Debug, PartialEq, Eq, PartialOrd, Ord, Clone)]
struct Position {
    x: i32,
    y: i32,
}

impl GameBoard {
    fn new(length: usize) -> GameBoard {
        let mut tail_visited = BTreeSet::new();
        tail_visited.insert(Position::default());
        GameBoard {
            rope: vec![Position::default(); length],
            tail_visited,
        }
    }

    fn step(&mut self, instruction: &Instruction) {
        for _ in 0..instruction.distance {
            match instruction.direction {
                Direction::Down => self.rope[0].y -= 1,
                Direction::Up => self.rope[0].y += 1,
                Direction::Left => self.rope[0].x -= 1,
                Direction::Right => self.rope[0].x += 1,
            };

            for tail_i in 1..self.rope.len() {
                let head_i = tail_i - 1;
                let head = self.rope[head_i].clone();
                let tail = &mut self.rope[tail_i];

                let tail_must_move = (head.x - tail.x).abs() > 1 || (head.y - tail.y).abs() > 1;

                if tail_must_move {
                    if head.x > tail.x {
                        tail.x += 1;
                    } else if head.x < tail.x {
                        tail.x -= 1;
                    }

                    if head.y > tail.y {
                        tail.y += 1;
                    } else if head.y < tail.y {
                        tail.y -= 1;
                    }
                }
            }

            self.tail_visited
                .insert(self.rope[self.rope.len() - 1].clone());
        }
    }
}