Solution for day 1
commit
88dd4fe6a7
|
@ -0,0 +1 @@
|
|||
/target
|
|
@ -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"
|
|
@ -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]
|
File diff suppressed because it is too large
Load Diff
|
@ -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)
|
||||
}
|
|
@ -0,0 +1 @@
|
|||
pub mod day_1;
|
|
@ -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());
|
||||
}
|
Reference in New Issue