summaryrefslogtreecommitdiffstats
path: root/2023/rs/code/one/src/main.rs
blob: 638b9a5398fc97f109f1ac9531080d7114d0e0f0 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
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}");
}