summaryrefslogblamecommitdiffstats
path: root/2023/rs/code/one/src/main.rs
blob: 638b9a5398fc97f109f1ac9531080d7114d0e0f0 (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;

    let mut indexoff = 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[i..].starts_with(num) {
            if d1 == 0 { d1 = i2 as u8 + b'1'; }
            d2 = i2 as u8 + b'1';
            break;
          }
        }
      }
    }
    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}");
}