summaryrefslogtreecommitdiff
path: root/2018/src/day14.rs
blob: ed9bb741b48227c7c8150e9d3edfc9f256c7fc2e (plain)
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
use std::io;
use std::io::BufRead;

fn simulate(list: &mut Vec<u8>, ptr1: &mut usize, ptr2: &mut usize) {
    let n1 = (list[*ptr1] + list[*ptr2]) / 10;
    let n2 = (list[*ptr1] + list[*ptr2]) % 10;

    if n1 != 0 { list.push(n1); }
    list.push(n2);

    *ptr1 = (*ptr1 + list[*ptr1] as usize + 1) % list.len();
    *ptr2 = (*ptr2 + list[*ptr2] as usize + 1) % list.len();
}

pub fn main<T: BufRead>(reader: T) -> io::Result<(String, String)> {
    let basestr = reader.lines().next().unwrap().unwrap();
    let basenum = basestr.parse::<usize>().unwrap();

    let mut list: Vec<u8> = Vec::with_capacity(basenum + 11);
    list.push(3);
    list.push(7);
    let mut ptr1 = 0;
    let mut ptr2 = 1;

    while list.len() < basenum + 10 {
        simulate(&mut list, &mut ptr1, &mut ptr2);
    }

    let part1 = String::from_utf8(list[basenum..basenum+10].iter().map(|n| n + 48).collect()).unwrap();

    let mut part2 = 0;

    let needle: Vec<u8> = basestr.as_bytes().iter().map(|n| n - 48).collect();
    for i in 0.. {
        if list.len() < i + needle.len() {
            simulate(&mut list, &mut ptr1, &mut ptr2);
        }

        if list[i..i+needle.len()] == *needle {
            part2 = i;
            break;
        }
    }

    Ok((part1, part2.to_string()))
}