Post

Advent of Code 2024 - Day 4

Part 1 : Ceres Search

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
use std::{fs::File, io::{self, Read}};

fn get_row(str_input: &String) -> Vec<Vec<char>> {
    let mut array_2d: Vec<Vec<char>> = Vec::new();

    for line in str_input.lines() {
        let row: Vec<char> = line.chars().collect();
        array_2d.push(row);
    }
    array_2d
}

fn main() -> io::Result<()>{
    let mut file = File::open("input1.txt")?;
    let mut str_input = String::new();
    let array_2d: Vec<Vec<char>>;
    let mut result: i32 = 0;
    let directions: [(isize, isize); 8] = [
        (0, 1),     // à droite
        (0, -1),    // à gauhe
        (-1, 0),    // en haut
        (1, 0),     // en bas
        (-1, 1),    // en haut + droite
        (-1, -1),   // en haut + gauche
        (1, 1),     // en bas + droite
        (1, -1)     // en bas + gauche
    ];
    let xmas: [char; 4] = ['X','M','A','S'];

    file.read_to_string(&mut str_input)?;
    array_2d = get_row(&str_input);
    for y in 0..array_2d.len() {
        for x in 0..array_2d[0].len() {
            if array_2d[y][x] == xmas[0] {
                for direction in directions {
                    let mut matched = true;

                    for i in 1..xmas.len() {
                        let new_y = y as isize + direction.0 * i as isize;
                        let new_x = x as isize + direction.1 * i as isize;

                        if new_y < 0 || new_x < 0 ||
                           new_y >= array_2d.len() as isize ||
                           new_x >= array_2d[0].len() as isize {
                            matched = false;
                            break;
                        }

                        if array_2d[new_y as usize][new_x as usize] != xmas[i] {
                            matched = false;
                            break;
                        }
                    }

                    if matched {
                        result += 1;
                    }
                }
            }
        }
    }

    println!("PART 1 : {}", result);

    Ok(())
}
This post is licensed under CC BY 4.0 by the author.