summaryrefslogblamecommitdiffstats
path: root/2023/rs/code/one/src/main.rs
blob: 1b04f08d0b384df1cc7c88e645760266321d70d0 (plain) (tree)














































                                                                                                             
static INPUT: &[u8] = include_bytes!("input.txt");

static NUMS: &[&[u8]] = &[ b"one", b"two", b"three", b"four", b"five", b"six", b"seven", b"eight", b"nine" ];

fn main() {
  let valueified = INPUT.split(|c| *c == b'\n').filter(|s| !s.is_empty());

  let calvals = valueified.clone().map(|s| {
    let mut d1 = 0;
    let mut d2 = 0;
    for c in s {
      if *c >= b'0' && *c <= b'9' {
        if d1 == 0 { d1 = *c; }
        d2 = *c;
      }
    }
    if d1 != 0 { ((d1 - b'0') * 10 + (d2 - b'0')) as u32 } else { 0 }
  });

  let sum = calvals.sum::<u32>();
  println!("Sum of Calibration Values: {sum}");

  let calvals = valueified.map(|s| {
    let mut d1 = 0;
    let mut d2 = 0;
    for i in 0..s.len() {
      let c = s[i];
      if c >= b'0' && c <= b'9' {
        if d1 == 0 { d1 = c; }
        d2 = c;
      }
      else {
        for i2 in 0..NUMS.len() {
          let num = NUMS[i2];
          if s.len() >= i + num.len() && &s[i..i+num.len()] == num {
            if d1 == 0 { d1 = i2 as u8 + b'1'; }
            d2 = i2 as u8 + b'1';
          }
        }
      }
    }
    if d1 != 0 { ((d1 - b'0') * 10 + (d2 - b'0')) as u32 } else { 0 }
  });

  let sum = calvals.sum::<u32>();
  println!("Sum of (word-included) Calibration Values: {sum}");
}