~cdv/aoc-2018-rs

2c55474e25ed7dc7138847945c87f8f148e7892d — Christopher Vittal 2 years ago f727439
Minor optimization

Don't grow line if we don't have to.
1 files changed, 10 insertions(+), 14 deletions(-)

M src/bin/day12.rs
M src/bin/day12.rs => src/bin/day12.rs +10 -14
@@ 48,19 48,15 @@ fn last(l: &[u8]) -> [u8; 4] {
     rule(&[l[n - 1], b'.', b'.', b'.', b'.'])]
}

fn generation(line: Vec<u8>, zero: usize) -> (Vec<u8>, usize) {
fn generation(line: Vec<u8>, zero: isize) -> (Vec<u8>, isize) {
    let first = [rule(&[b'.', b'.', b'.', b'.', line[0]]),
                 rule(&[b'.', b'.', b'.', line[0], line[1]]),
                 rule(&[b'.', b'.', line[0], line[1], line[2]]),
                 rule(&[b'.', line[0], line[1], line[2], line[3]])];
    let first = if first[0] == b'.' {
        if first[1] == b'.' {
            &first[2..]
        } else {
            &first[1..]
        }
    let first = if let Some(p) = first.iter().position(|&b| b == b'#') {
        &first[p..]
    } else {
        &first[..]
        &[]
    };

    let next = line.windows(5).map(rule);


@@ 71,12 67,12 @@ fn generation(line: Vec<u8>, zero: usize) -> (Vec<u8>, usize) {
        &[]
    };
    (first.iter().cloned().chain(next).chain(last.iter().cloned()).collect::<Vec<_>>(),
     zero + first.len() - 2)
     zero + first.len() as isize - 2)
}

fn plant_sum(line: &[u8], zero: usize) -> isize {
fn plant_sum(line: &[u8], zero: isize) -> isize {
    line.iter().enumerate().map(|(i, &e)| if e == b'#' {
        (i as isize - zero as isize)
        (i as isize - zero)
    } else {
        0
    }).sum()


@@ 86,7 82,7 @@ fn main() {
    let mut line = Vec::from(INPUT);
    let mut zero = 0;

    for _ in 0..20 {
    for _ in 1..=20 {
        let gen = generation(line, zero);
        line = gen.0;
        zero = gen.1;


@@ 98,9 94,8 @@ fn main() {
    // Assumption, difference stabilizes eventually, leading to a linear formula
    let mut heuristic = 0;
    let mut diff = 0;
    let mut end_gen = 20;
    let mut end_gen = 21;
    loop {
        end_gen += 1;
        let gen = generation(line, zero);
        line = gen.0;
        zero = gen.1;


@@ 115,6 110,7 @@ fn main() {
            break;
        }
        diff = sum - prev;
        end_gen += 1;
    };
    println!("  2: {}", sum + (50_000_000_000 - end_gen) * diff);
}