feat: day1
Signed-off-by: Louis Vallat <louis@louis-vallat.xyz>
This commit is contained in:
commit
f05a2a1a4d
2
.gitignore
vendored
Normal file
2
.gitignore
vendored
Normal file
@ -0,0 +1,2 @@
|
||||
target
|
||||
Cargo.lock
|
11
.gitlab-ci.yml
Normal file
11
.gitlab-ci.yml
Normal file
@ -0,0 +1,11 @@
|
||||
default:
|
||||
image: rust
|
||||
|
||||
stages:
|
||||
- build
|
||||
|
||||
day-1:
|
||||
stage: build
|
||||
script:
|
||||
- cd day1; cargo run --release ./input
|
||||
|
8
day1/Cargo.toml
Normal file
8
day1/Cargo.toml
Normal file
@ -0,0 +1,8 @@
|
||||
[package]
|
||||
name = "day1"
|
||||
version = "0.1.0"
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
2237
day1/input
Normal file
2237
day1/input
Normal file
File diff suppressed because it is too large
Load Diff
41
day1/src/main.rs
Normal file
41
day1/src/main.rs
Normal file
@ -0,0 +1,41 @@
|
||||
use std::{fs, env};
|
||||
|
||||
fn read_input(path: &str) -> String {
|
||||
return fs::read_to_string(path).expect("Cannot read file.");
|
||||
}
|
||||
|
||||
fn parse_input(s: &str) -> Vec<Vec<i32>> {
|
||||
let mut ret = vec![];
|
||||
let mut buffer = vec![];
|
||||
for l in s.lines() {
|
||||
if l.is_empty() {
|
||||
ret.push(buffer.clone());
|
||||
buffer.clear();
|
||||
} else {
|
||||
buffer.push(l.parse::<i32>().unwrap())
|
||||
}
|
||||
}
|
||||
return ret;
|
||||
}
|
||||
|
||||
fn sort_and_sum(input: &Vec<Vec<i32>>) -> Vec<i32> {
|
||||
let mut summed = input.iter()
|
||||
.map(|i| i.iter().sum()).collect::<Vec<i32>>();
|
||||
summed.sort();
|
||||
return summed;
|
||||
}
|
||||
|
||||
fn sum_of_last_n(sorted: &Vec<i32>, n: usize) -> i32 {
|
||||
return sorted.iter().rev().take(n).sum();
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let args: Vec<String> = env::args().collect();
|
||||
for arg in args.iter().skip(1) {
|
||||
println!("[{}]", &arg);
|
||||
let vec_in = parse_input(&read_input(&arg));
|
||||
let sorted = sort_and_sum(&vec_in);
|
||||
println!("\t[Part 1] => Answer is '{}'.", sum_of_last_n(&sorted, 1));
|
||||
println!("\t[Part 2] => Answer is '{}'.", sum_of_last_n(&sorted, 3));
|
||||
}
|
||||
}
|
Loading…
Reference in New Issue
Block a user