Solution for day 1

master
Jef Roosens 2021-12-02 14:44:50 +01:00
commit 88dd4fe6a7
Signed by: Jef Roosens
GPG Key ID: B580B976584B5F30
7 changed files with 2082 additions and 0 deletions

1
.gitignore vendored 100644
View File

@ -0,0 +1 @@
/target

7
Cargo.lock generated 100644
View File

@ -0,0 +1,7 @@
# This file is automatically @generated by Cargo.
# It is not intended for manual editing.
version = 3
[[package]]
name = "aoc"
version = "0.1.0"

8
Cargo.toml 100644
View File

@ -0,0 +1,8 @@
[package]
name = "aoc"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

2000
input/day1 100644

File diff suppressed because it is too large Load Diff

58
src/days/day_1.rs 100644
View File

@ -0,0 +1,58 @@
use std::fs::File;
use std::io;
use std::io::BufRead;
use std::io::BufReader;
pub fn part1() -> io::Result<u32> {
let file = File::open("input/day1")?;
let reader = BufReader::new(file);
let mut first = true;
let mut previous = 0;
let mut count = 0;
for line in reader.lines() {
let num: u32 = line?.parse().unwrap();
if !first && num > previous {
count += 1;
}
previous = num;
first = false;
}
Ok(count)
}
pub fn part2() -> io::Result<u32> {
let file = File::open("input/day1")?;
let reader = BufReader::new(file);
let mut vals: [u32; 3] = [0, 0, 0];
let mut count = 0;
for (i, line) in reader.lines().enumerate() {
let num: u32 = line?.parse().unwrap();
if i < 3 {
vals[i] = num;
} else {
// Calculate the previous sum
let sum = vals[0] + vals[1] + vals[2];
// Shift the values
vals[0] = vals[1];
vals[1] = vals[2];
vals[2] = num;
let new_sum = vals[0] + vals[1] + vals[2];
if new_sum > sum {
count += 1;
}
}
}
Ok(count)
}

1
src/days/mod.rs 100644
View File

@ -0,0 +1 @@
pub mod day_1;

7
src/main.rs 100644
View File

@ -0,0 +1,7 @@
mod days;
fn main() {
// Day 1
println!("Day 1, part 1: {}", days::day_1::part1().unwrap());
println!("Day 1, part 2: {}", days::day_1::part2().unwrap());
}