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

  • @anonymouse@sh.itjust.works
    link
    fedilink
    4
    edit-2
    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
      link
      fedilink
      21 year ago

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

    • @Walnut356@programming.dev
      link
      fedilink
      1
      edit-2
      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
        link
        fedilink
        11 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!