2 changed files with 106 additions and 1 deletions
@ -0,0 +1,79 @@ |
|||
use std::collections::HashSet; |
|||
|
|||
const DEBUG : bool = false; |
|||
|
|||
pub struct Data { |
|||
input : Vec<i32>, |
|||
} |
|||
|
|||
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::<i32>().unwrap()); |
|||
|
|||
} |
|||
self.input.push(mult * sline.parse::<i32>().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<i32> = 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 |
|||
} |
|||
} |
|||
@ -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<String,std::io::Error> { |
|||
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), |
|||
} |
|||
} |
|||
Loading…
Reference in new issue