23
submitted 1 year ago* (last edited 1 year ago) by Ategon@programming.dev to c/advent_of_code@programming.dev

Day 6: Wait for It


Megathread guidelines

  • Keep top level comments as only solutions, if you want to say something other than a solution put it in a new post. (replies to comments can be whatever)
  • Code block support is not fully rolled out yet but likely will be in the middle of the event. Try to share solutions as both code blocks and using something such as https://topaz.github.io/paste/ , pastebin, or github (code blocks to future proof it for when 0.19 comes out and since code blocks currently function in some apps and some instances as well if they are running a 0.19 beta)

FAQ

you are viewing a single comment's thread
view the rest of the comments
[-] anonymouse@sh.itjust.works 4 points 1 year ago* (last edited 1 year ago)

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
}

[-] hades@lemm.ee 2 points 1 year ago

Somewhere on the way you seem to have converted ampersands to HTML entities :)

[-] janAkali@lemmy.one 3 points 1 year ago* (last edited 1 year ago)

It's caused by lemmy code blocks. They don't handle & correctly. See.

[-] hades@lemm.ee 1 points 1 year ago

Ah. Never noticed that before :)

[-] Walnut356@programming.dev 1 points 1 year ago* (last edited 1 year ago)

I'm no rust expert, but:

you can use into_iter() instead of iter() to get owned data (if you're not going to use the original container again). With into_iter() you dont have to deref the values every time which is nice.

Also it's small potatoes, but calling input.lines().collect() allocates a vector (that isnt ever used again) when lines() returns an iterator that you can use directly. You can instead pass lines.next().unwrap() into your functions directly.

Strings have a method called split_whitespace() (also a split_ascii_whitespace()) that returns an iterator over tokens separated by any amount of whitespace. You can then call .collect() with a String turbofish (i'd type it out but lemmy's markdown is killing me) on that iterator. Iirc that ends up being faster because replacing characters with an empty character requires you to shift all the following characters backward each time.

Overall really clean code though. One of my favorite parts of using rust (and pain points of going back to other languages) is the crazy amount of helper functions for common operations on basic types.

Edit: oh yeah, also strings have a .parse() method to converts it to a number e.g. data.parse() where the parse takes a turbo fish of the numeric type. As always, turbofishes arent required if rust already knows the type of the variable it's being assigned to.

[-] anonymouse@sh.itjust.works 1 points 1 year ago

Thanks for making some time to check my code, really appreciated! the split_whitespace is super useful, for some reason I expected it to just split on single spaces, so I was messing with trim() stuff the whole time :D. Could immediately apply this feedback to the Challenge of today! I've now created a general function I can use for these situations every time:

    input.split_whitespace()
        .map(|m| m.parse().expect("can't parse string to int"))
        .collect()
}

Thanks again!

this post was submitted on 06 Dec 2023
23 points (96.0% liked)

Advent Of Code

920 readers
90 users here now

An unofficial home for the advent of code community on programming.dev!

Advent of Code is an annual Advent calendar of small programming puzzles for a variety of skill sets and skill levels that can be solved in any programming language you like.

AoC 2024

Solution Threads

M T W T F S S
1
2 3 4 5 6 7 8
9 10 11 12 13 14 15
16 17 18 18 20 21 22
23 24 25

Rules/Guidelines

Relevant Communities

Relevant Links

Credits

Icon base by Lorc under CC BY 3.0 with modifications to add a gradient

console.log('Hello World')

founded 1 year ago
MODERATORS