summaryrefslogtreecommitdiff
path: root/2018/src
diff options
context:
space:
mode:
Diffstat (limited to '2018/src')
-rw-r--r--2018/src/day1.rs25
-rw-r--r--2018/src/main.rs78
2 files changed, 103 insertions, 0 deletions
diff --git a/2018/src/day1.rs b/2018/src/day1.rs
new file mode 100644
index 0000000..741f5b3
--- /dev/null
+++ b/2018/src/day1.rs
@@ -0,0 +1,25 @@
+use std::io;
+use std::io::BufRead;
+use std::collections::HashSet;
+
+pub fn main<T: BufRead>(reader: T) -> io::Result<()> {
+ let values: Vec<i64> =
+ reader.lines().map(|l| l.unwrap().parse::<i64>().unwrap()).collect();
+
+ println!("{}", values.iter().sum::<i64>());
+
+ let mut seen = HashSet::new();
+ seen.insert(0);
+
+ let mut res = 0;
+ for val in values.iter().cycle() {
+ res += val;
+ if seen.contains(&res) {
+ println!("{}", res);
+ return Ok(());
+ } else {
+ seen.insert(res);
+ }
+ }
+ unreachable!()
+}
diff --git a/2018/src/main.rs b/2018/src/main.rs
new file mode 100644
index 0000000..7e683ca
--- /dev/null
+++ b/2018/src/main.rs
@@ -0,0 +1,78 @@
+extern crate argparse;
+
+use std::io;
+use std::io::{BufRead, BufReader, Error, ErrorKind};
+use std::fs::File;
+use std::process::exit;
+use argparse::{ArgumentParser, StoreTrue, Store};
+
+mod day1;
+
+fn day_switch<T: BufRead>(day: i32, reader: T) -> io::Result<()> {
+ match day {
+ 1 => day1::main(reader),
+ _ => Err(Error::new(ErrorKind::Other, "Invalid day"))
+ }
+}
+
+struct Options {
+ use_stdin: bool,
+}
+
+fn run_day(day: i32, opts: &Options) -> io::Result<()> {
+ if opts.use_stdin {
+ let stdin = io::stdin();
+ day_switch(day, BufReader::new(stdin))
+ } else {
+ match File::open(format!("../input/{}.txt", day)) {
+ Ok(f) => day_switch(day, BufReader::new(f)),
+ Err(_) => Err(Error::new(ErrorKind::Other, format!("No input file for day {}", day)))
+ }
+ }
+}
+
+fn error_handler<F>(func: F) -> io::Result<()>
+ where F: Fn() -> io::Result<()> {
+
+ match func() {
+ Ok(()) => Ok(()),
+ Err(err) => {
+ if err.kind() == ErrorKind::Other {
+ println!("Error: {}", err);
+ exit(1)
+ } else {
+ Err(err)
+ }
+ }
+ }
+}
+
+fn main() -> io::Result<()> {
+ let mut day_string = String::new();
+ let mut options = Options {
+ use_stdin: false
+ };
+
+ {
+ let mut parser = ArgumentParser::new();
+ parser.set_description("AOC 2018 solutions by Tom Smeding");
+ parser.refer(&mut options.use_stdin)
+ .add_option(&["-s", "--stdin"], StoreTrue,
+ "Read from stdin");
+ parser.refer(&mut day_string)
+ .add_argument("day", Store, "Day to execute");
+ parser.parse_args_or_exit();
+ }
+
+ error_handler(||
+ match day_string.parse::<i32>() {
+ Ok(day) => run_day(day, &options),
+ Err(_) => {
+ for day in 1..1 {
+ run_day(day, &options)?;
+ }
+ Ok(())
+ }
+ }
+ )
+}