summaryrefslogtreecommitdiff
path: root/2020/src/bin/day_10.rs
blob: 7ef4fa2ba102653f42086a66cd6c2e9d52b7b9e9 (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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
use bevy::{app::AppExit, prelude::*};
use std::io::{BufRead, BufReader};
use std::{collections::BTreeMap, fs::File};

fn main() {
    App::build()
        .add_resource(WindowDescriptor {
            title: "Advent of Code".to_string(),
            width: 1920,
            height: 1080,
            ..Default::default()
        })
        .add_resource(ClearColor(Color::rgb(0., 0., 0.)))
        .add_startup_system(setup_camera.system())
        .add_startup_system(read_input_file.system())
        .add_startup_stage("differences")
        .add_startup_system_to_stage("differences", add_min_differences.system())
        .add_startup_system_to_stage("differences", add_all_differences.system())
        .add_startup_stage("report")
        .add_startup_system_to_stage("report", print_difference_stats.system())
        .add_system(add_next_paths_to_end_sum.system())
        .add_system(report_full_paths_to_end.system())
        .add_plugins(DefaultPlugins)
        .run();
}

fn setup_camera(mut commands: Commands) {
    commands.spawn(Camera2dComponents::default());
}

#[derive(PartialEq, Eq, PartialOrd, Ord)]
struct MinJoltDiff(i64);
#[derive(Clone)]
struct NextJolts(Vec<Entity>);
struct Jolts(i64);
struct PathsToEnd(u64);

fn read_input_file(mut commands: Commands) {
    let f = File::open("./inputs/day_10.txt").unwrap();

    commands.spawn((Jolts(0),));
    for line in BufReader::new(f).lines() {
        let line = line.unwrap();
        let line = line.trim();
        let num = line.parse().unwrap();

        commands.spawn((Jolts(num),));
    }
}

fn add_min_differences(
    mut commands: Commands,
    jolts_query: Query<(Entity, &Jolts, Option<&MinJoltDiff>)>,
) {
    for (entity, jolts, jolt_diff) in jolts_query.iter() {
        if jolt_diff.is_none() {
            let min_increase = jolts_query
                .iter()
                .map(|(_, other_jolts, _)| other_jolts)
                .filter(|other_jolts| other_jolts.0 > jolts.0)
                .map(|other_jolts| MinJoltDiff(other_jolts.0 - jolts.0))
                .min()
                .unwrap_or(MinJoltDiff(3));
            commands.insert_one(entity, min_increase);
        }
    }
}

fn add_all_differences(mut commands: Commands, jolts_query: Query<(Entity, &Jolts)>) {
    for (entity, jolts) in jolts_query.iter() {
        let next_entities = jolts_query
            .iter()
            .filter(|(_, other_jolts)| other_jolts.0 > jolts.0 && other_jolts.0 - jolts.0 <= 3)
            .map(|(other_entity, _)| other_entity)
            .collect();
        commands.insert_one(entity, NextJolts(next_entities));
    }
}

fn print_difference_stats(diffs: Query<&MinJoltDiff>) {
    let mut buckets: BTreeMap<i64, usize> = BTreeMap::new();
    for diff in diffs.iter() {
        *buckets.entry(diff.0).or_insert(0) += 1;
    }
    println!("Buckets: {:?}", buckets);

    println!(
        "Bucket 1 * Bucket 3: {}",
        buckets.get(&1).unwrap_or(&0) * buckets.get(&3).unwrap_or(&0)
    );
}

fn add_next_paths_to_end_sum(
    mut commands: Commands,
    potential_to_add: Query<Without<PathsToEnd, (Entity, &NextJolts)>>,
    already_added: Query<&PathsToEnd>,
) {
    for (entity, next) in potential_to_add.iter() {
        if next.0.is_empty() {
            commands.insert_one(entity, PathsToEnd(1));
        } else {
            let next_paths: Result<Vec<&PathsToEnd>, _> = next
                .0
                .iter()
                .map(|next_entity| already_added.get(*next_entity))
                .collect();
            if let Ok(next_paths) = next_paths {
                let sum = next_paths.iter().map(|paths| paths.0).sum();
                commands.insert_one(entity, PathsToEnd(sum));
            }
        }
    }
}

fn report_full_paths_to_end(
    mut exit_events: ResMut<Events<AppExit>>,
    jolts: &Jolts,
    paths: &PathsToEnd,
) {
    if jolts.0 == 0 {
        println!("Paths from the start to the end: {}", paths.0);
        exit_events.send(AppExit);
    }
}