Welcome everyone to the 2023 advent of code! Thank you all for stopping by and participating in it in programming.dev whether youre new to the event or doing it again.

This is an unofficial community for the event as no official spot exists on lemmy but ill be running it as best I can with Sigmatics modding as well. Ill be running a solution megathread every day where you can share solutions with other participants to compare your answers and to see the things other people come up with


Day 1: Trebuchet?!


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/ or pastebin (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


🔒This post will be unlocked when there is a decent amount of submissions on the leaderboard to avoid cheating for top spots

🔓 Edit: Post has been unlocked after 6 minutes

  • Joey@programming.dev
    link
    fedilink
    arrow-up
    4
    ·
    edit-2
    7 months ago

    My solution in rust. I’m sure there’s a lot more clever ways to do it but this is what I came up with.

    Code
    use std::{io::prelude::*, fs::File, path::Path, io };
    
    fn main() 
    {
        run_solution(false); 
    
        println!("\nPress enter to continue");
        let mut buffer = String::new();
        io::stdin().read_line(&mut buffer).unwrap();
    
        run_solution(true); 
    }
    
    fn run_solution(check_for_spelled: bool)
    {
        let data = load_data("data/input");
    
        println!("\nProcessing Data...");
    
        let mut sum: u64 = 0;
        for line in data.lines()
        {
            // Doesn't seem like the to_ascii_lower call is needed but... just in case
            let first = get_digit(line.to_ascii_lowercase().as_bytes(), false, check_for_spelled);
            let last = get_digit(line.to_ascii_lowercase().as_bytes(), true, check_for_spelled);
    
    
            let num = (first * 10) + last;
    
            // println!("\nLine: {} -- First: {}, Second: {}, Num: {}", line, first, last, num);
            sum += num as u64;
        }
    
        println!("\nFinal Sum: {}", sum);
    }
    
    fn get_digit(line: &[u8], from_back: bool, check_for_spelled: bool) -> u8
    {
        let mut range: Vec = (0..line.len()).collect();
        if from_back
        {
            range.reverse();
        }
    
        for i in range
        {
            if is_num(line[i])
            {
                return (line[i] - 48) as u8;
            }
    
            if check_for_spelled
            {
                if let Some(num) = is_spelled_num(line, i)
                {
                    return num;
                }
            }
        }
    
        return 0;
    }
    
    fn is_num(c: u8) -> bool
    {
        c >= 48 && c <= 57
    }
    
    fn is_spelled_num(line: &[u8], start: usize) -> Option
    {
        let words = ["one", "two", "three", "four", "five", "six", "seven", "eight", "nine"];
    
        for word_idx in 0..words.len()
        {
            let mut i = start;
            let mut found = true;
            for c in words[word_idx].as_bytes()
            {
                if i < line.len() && *c != line[i]
                {
                    found = false;
                    break;
                }
                i += 1;
            }
    
            if found && i <= line.len()
            {
                return Some(word_idx as u8 + 1);
            }
        }
    
        return None;
    }
    
    fn load_data(file_name: &str) -> String
    {
        let mut file = match File::open(Path::new(file_name))
        {
            Ok(file) => file,
            Err(why) => panic!("Could not open file {}: {}", Path::new(file_name).display(), why),
        };
    
        let mut s = String::new();
        let file_contents = match file.read_to_string(&mut s) 
        {
            Err(why) => panic!("couldn't read {}: {}", Path::new(file_name).display(), why),
            Ok(_) => s,
        };
        
        return file_contents;
    }
    
    • CannotSleep420@lemmygrad.ml
      link
      fedilink
      English
      arrow-up
      3
      ·
      7 months ago

      One small thing that would make it easier to read would be to use (I don’t know what the syntax is called) as opposed to the magic numbers for getting the ascii code for a character as a u8, e.g. b'0' instead of 48.

      • Joey@programming.dev
        link
        fedilink
        arrow-up
        3
        ·
        7 months ago

        Oh yeah that’s a good point. I have seen that before but I didn’t think of it at the time.