day01 both
This commit is contained in:
2
src/lib.rs
Normal file
2
src/lib.rs
Normal file
@@ -0,0 +1,2 @@
|
||||
pub mod tasks;
|
||||
pub mod utils;
|
||||
4
src/main.rs
Normal file
4
src/main.rs
Normal file
@@ -0,0 +1,4 @@
|
||||
fn main() {
|
||||
aoc_2018::tasks::day01::task1();
|
||||
aoc_2018::tasks::day01::task2();
|
||||
}
|
||||
36
src/tasks/day01.rs
Normal file
36
src/tasks/day01.rs
Normal file
@@ -0,0 +1,36 @@
|
||||
use std::collections::HashSet;
|
||||
use utils;
|
||||
|
||||
pub fn task1() {
|
||||
let contents = utils::read_file("input/day01.txt");
|
||||
|
||||
let mut frequency = 0;
|
||||
for line in contents.split_whitespace() {
|
||||
let number: i32 = line.parse().unwrap();
|
||||
frequency += number;
|
||||
}
|
||||
|
||||
println!("Result: {}", frequency);
|
||||
}
|
||||
|
||||
pub fn task2() {
|
||||
let contents = utils::read_file("input/day01.txt");
|
||||
|
||||
let mut seen = HashSet::new();
|
||||
|
||||
let mut frequency = 0;
|
||||
seen.insert(frequency);
|
||||
let changes: Vec<i32> = contents.lines().map(|line| line.parse().unwrap()).collect();
|
||||
|
||||
loop {
|
||||
for number in changes.iter() {
|
||||
frequency += number;
|
||||
if seen.contains(&frequency) {
|
||||
println!("{} was there already!", frequency);
|
||||
return;
|
||||
}
|
||||
|
||||
seen.insert(frequency);
|
||||
}
|
||||
}
|
||||
}
|
||||
1
src/tasks/mod.rs
Normal file
1
src/tasks/mod.rs
Normal file
@@ -0,0 +1 @@
|
||||
pub mod day01;
|
||||
11
src/utils.rs
Normal file
11
src/utils.rs
Normal file
@@ -0,0 +1,11 @@
|
||||
use std::fs::File;
|
||||
use std::io::prelude::*;
|
||||
|
||||
pub fn read_file(path: &str) -> String {
|
||||
let mut f = File::open(path).expect(&format!("file '{}' not found", path));
|
||||
|
||||
let mut contents = String::new();
|
||||
f.read_to_string(&mut contents)
|
||||
.expect("something went wrong reading the file");
|
||||
contents
|
||||
}
|
||||
Reference in New Issue
Block a user