diff --git a/src/day1.rs b/src/day1.rs new file mode 100644 index 0000000..bd7b547 --- /dev/null +++ b/src/day1.rs @@ -0,0 +1,79 @@ +use std::collections::HashSet; + +const DEBUG : bool = false; + +pub struct Data { + input : Vec, +} + +impl Data { + pub fn new() -> Data { + Data { + input : Vec::new(), + } + } + + pub fn parse(&mut self, input: String) { + for line in input.split("\n") { + let mut sline = line.to_string(); + if DEBUG { + print!("{} -> ", sline); + } + if sline.len() >= 2 { + let mult: i32 = match sline.remove(0) { + '+' => 1, + '-' => -1, + _ => 0, + }; + if DEBUG { + print!("{}, {}", mult, sline.parse::().unwrap()); + + } + self.input.push(mult * sline.parse::().unwrap()); + } + } + if DEBUG { + for f in self.input.iter() { + print!("{} ",f); + } + } + } + + pub fn challenge1(&mut self) -> i32 { + let mut result : i32 = 0; + for f in self.input.iter() { + result = result + f; + } + result + } + + pub fn challenge2(&mut self) -> i32 { + let mut dup : HashSet = HashSet::new(); + let mut found : bool = false; + let mut result : i32 = 0; + while !found { + for i in self.input.clone() { + if !found { + result = result + i; + + if dup.contains(&result) { + found = true; + if DEBUG { + println!("{} == elem", result); + } + } + else { + dup.insert(result); + if DEBUG { + for elem in dup.clone() { + print!("{} ", elem); + } + println!("{} != elem", result); + } + } + } + } + } + result + } +} \ No newline at end of file diff --git a/src/main.rs b/src/main.rs index e7a11a9..24221c6 100644 --- a/src/main.rs +++ b/src/main.rs @@ -1,3 +1,29 @@ +use std::fs::File; +use std::io::Read; + +mod day1; + fn main() { - println!("Hello, world!"); + match read_file("day1.txt") { + Ok(input) => { + let mut d1 = day1::Data::new(); + d1.parse(input); + println!("Day1 Challenge1 result = {}",d1.challenge1()); + println!("Day1 Challenge2 result = {}",d1.challenge2()); + }, + Err(msg) => {println!("Error: {}", msg);}, + } } + +fn read_file(filename: &str) -> Result { + match File::open(filename) { + Ok(mut file) => { + let mut input = String::new(); + match file.read_to_string(&mut input) { + Ok(_) => Ok(input), + Err(msg) => Err(msg), + } + }, + Err(msg) => Err(msg), + } +} \ No newline at end of file