Skip to content
Snippets Groups Projects

AoC 2023 day 1

  • Clone with SSH
  • Clone with HTTPS
  • Embed
  • Share
    The snippet can be accessed without any authentication.
    Authored by s91149
    Edited
    main.rs 1.57 KiB
    fn main() {
        let input = std::fs::read_to_string("../inputs/input.txt").unwrap();
        println!("{}", input);
        part_1(&input);
        part_2(&input);
    }
    
    fn part_1(input: &str) {
        let sum: u64 = input
            .lines()
            .map(|line| {
                let numbers: Vec<char> = line.chars().filter(|c| c.is_ascii_digit()).collect();
                let number_string = format!("{}{}", numbers.first().unwrap(), numbers.last().unwrap());
                number_string.parse::<u64>().unwrap()
            })
            .sum();
        println!("part 1: {}", sum);
    }
    
    fn part_2(input: &str) {
        let number_words = [
            "one", "two", "three", "four", "five", "six", "seven", "eight", "nine",
        ];
    
        let sum: u64 = input
            .lines()
            .map(|line| {
                let chars: Vec<char> = line.chars().collect();
                let mut numbers = Vec::new();
    
                for (i, c) in line.chars().enumerate() {
                    if c.is_ascii_digit() {
                        numbers.push(chars[i].to_string());
                    } else {
                        let remaining: String = chars[i..].iter().collect();
                        let pos = number_words
                            .iter()
                            .position(|word| remaining.starts_with(word));
    
                        if let Some(pos) = pos {
                            numbers.push((pos + 1).to_string());
                        }
                    }
                }
    
                format!("{}{}", numbers.first().unwrap(), numbers.last().unwrap())
                    .parse::<u64>()
                    .unwrap()
            })
            .sum();
    
        println!("part 2: {}", sum);
    }
    0% Loading or .
    You are about to add 0 people to the discussion. Proceed with caution.
    Finish editing this message first!
    Please register or to comment