aboutsummaryrefslogtreecommitdiff
path: root/day08.rs
blob: 7c8436a805110072214ab20d689db92c7164b3a5 (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
use std::fs::File;
use std::io::{BufRead,BufReader};

fn part1(v: &mut Vec<i32>) -> i32 {
    let len = v[0];
    let mdl = v[1];

    let mut data = v.split_off(2);
    std::mem::swap(&mut data, v);
    
    let mut mds = (0..len).map(|_| part1(v)).sum::<i32>();
    
    let mut mdata = v.split_off(mdl as usize);
    std::mem::swap(&mut mdata, v);
    
    mds += mdata.iter().sum::<i32>();

    return mds;
}

fn part2(v: &mut Vec<i32>) -> i32 {
    let len = v[0];
    let mdl = v[1];
    let mut data = v.split_off(2);
    std::mem::swap(&mut data, v);
    
    let mds: Vec<i32> = (0..len).map(|_| part2(v)).collect();
    
    let mut mdata = v.split_off(mdl as usize);
    std::mem::swap(&mut mdata, v);

    if len == 0 {
        mdata.iter().sum::<i32>()
    } else {
        mdata.iter().map(|i| mds.get(*i as usize-1).unwrap_or(&0)).sum::<i32>()
    }
}

fn main() {
    let f = File::open("day08").unwrap();

    let v: Vec<i32> = BufReader::new(&f).lines()
        .next().unwrap()
        .unwrap().split(" ")
        .map(|n| n.parse().unwrap())
        .collect();

    println!("{}", part1(&mut v.clone()));
    println!("{}", part2(&mut v.clone()));
}