anonymouse

joined 1 year ago
[โ€“] anonymouse 4 points 1 year ago* (last edited 1 year ago) (5 children)

Rust

Feedback welcome! Feel like I'm getting the hand of Rust more and more.

use regex::Regex;
pub fn part_1(input: &str) {
    let lines: Vec<&str> = input.lines().collect();
    let time_data = number_string_to_vec(lines[0]);
    let distance_data = number_string_to_vec(lines[1]);

    // Zip time and distance into a single iterator
    let data_iterator = time_data.iter().zip(distance_data.iter());

    let mut total_possible_wins = 1;
    for (time, dist_req) in data_iterator {
        total_possible_wins *= calc_possible_wins(*time, *dist_req)
    }
    println!("part possible wins: {:?}", total_possible_wins);
}

pub fn part_2(input: &str) {
    let lines: Vec<&str> = input.lines().collect();
    let time_data = number_string_to_vec(&lines[0].replace(" ", ""));
    let distance_data = number_string_to_vec(&lines[1].replace(" ", ""));

    let total_possible_wins = calc_possible_wins(time_data[0], distance_data[0]);
    println!("part 2 possible wins: {:?}", total_possible_wins);
}

pub fn calc_possible_wins(time: u64, dist_req: u64) -> u64 {
    let mut ways_to_win: u64 = 0;

    // Second half is a mirror of the first half, so only calculate first part
    for push_time in 1..=time / 2 {
        // If a push_time crosses threshold the following ones will too so break loop
        if push_time * (time - push_time) > dist_req {
            // There are (time+1) options (including 0).
            // Subtract twice the minimum required push time, also removing the longest push times
            ways_to_win += time + 1 - 2 * push_time;
            break;
        }
    }
    ways_to_win
}

fn number_string_to_vec(input: &str) -> Vec {
    let regex_number = Regex::new(r"\d+").unwrap();
    let numbers: Vec = regex_number
        .find_iter(input)
        .filter_map(|m| m.as_str().parse().ok())
        .collect();
    numbers
}

[โ€“] anonymouse 2 points 1 year ago

Same here, yesterday felt like a trap, but didn't run into anything today?

[โ€“] anonymouse 1 points 1 year ago

Just getting started with Rust, part 1 took a long time. Really amazed when I saw part 2, just needed to add 2 lines and was done due to the approach I had taken. Feedback more than welcome!

use std::{
    cmp, fs,
    io::{BufRead, BufReader},
};

fn main() {
    cube_conundrum_complete();
}

fn cube_conundrum_complete() {
    // Load the data file
    let filename = "./data/input_data/day_2_cubes.txt";
    let file = match fs::File::open(filename) {
        Ok(f) => f,
        Err(e) => {
            eprintln!("Error opening file: {}", e);
            return;
        }
    };
    let reader = BufReader::new(file);

    // iniatiate final results
    let mut total = 0;
    let mut total_power = 0;

    // loop over the games in the file
    for _line in reader.lines() {
        // Handle the data and extract game number and maximum number of cubes per color
        let (game_number, max_green, max_red, max_blue) = cube_conundrum_data_input(_line.unwrap());

        // Calculate the power for the day 2 result
        total_power += max_green * max_red * max_blue;

        //Calculate if the game was possible with the given number of cubes
        let result = cube_conundrum_game_possible(game_number, max_green, max_red, max_blue);
        total += result;
    }

    // print the final results
    println!("total part 1: {}", total);
    println!("total part 2: {}", total_power);
}

fn cube_conundrum_data_input(game_input: String) -> (i32, i32, i32, i32) {
    // Split the game number from the draws
    let (game_part, data_part) = game_input.split_once(":").unwrap();

    // Select the number of the round and parse into an integer
    let game_number: i32 = game_part
        .split_once(" ")
        .unwrap()
        .1
        .parse::()
        .expect("could not parse gamenumber to integer");

    // Split the data part into a vector both split on , and ; cause we only care about he maximum per color
    let parts: Vec<&str> = data_part
        .split(|c| c == ',' || c == ';')
        .map(|part| part.trim())
        .collect();

    // Set the intial values for the maximum per color to 0
    let (mut max_green, mut max_red, mut max_blue) = (0, 0, 0);

    // Loop over the different draws split them into color and nubmer of cubes, update maximum number of cubes
    for part in parts.iter() {
        let (nr_cubes_text, color) = part.split_once(" ").unwrap();
        let nr_cubes = nr_cubes_text
            .parse::()
            .expect("could not parse to integer");
        match color {
            "green" => max_green = cmp::max(max_green, nr_cubes),
            "red" => max_red = cmp::max(max_red, nr_cubes),
            "blue" => max_blue = cmp::max(max_blue, nr_cubes),
            _ => println!("unknown color: {}", color),
        };
    }

    return (game_number, max_green, max_red, max_blue);
}

fn cube_conundrum_game_possible(
    game_number: i32,
    max_green: i32,
    max_red: i32,
    max_blue: i32,
) -> i32 {
    // Compare the number of seen cubes per game with the proposed number. Return the game number if it was possible, otherwise 0
    let (comparison_red, comparison_green, comparison_blue) = (12, 13, 14);
    if max_green > comparison_green || max_red > comparison_red || max_blue > comparison_blue {
        return 0;
    };
    game_number
}
[โ€“] anonymouse 2 points 1 year ago

Thanks, used this as input for reading the Day 2 file and looping the lines, just getting started with rust :)

[โ€“] anonymouse 6 points 1 year ago (1 children)

I think it's related to the replacement of words with digits. There are some overlapping words, for example in "eightwothree" the "t" is used for both "eighT" and "Two". In this case the order of replacement differs your result. It either becomes "8wo3" or "eigh23".

view more: โ€น prev next โ€บ