summaryrefslogtreecommitdiff
path: root/aoc15
diff options
context:
space:
mode:
authorJustin Worthe <justin.worthe@entelect.co.za>2016-12-15 12:50:14 +0200
committerJustin Worthe <justin.worthe@entelect.co.za>2016-12-15 12:50:14 +0200
commitb835d5cc786f284c1f1752fb01c135b267f9bb87 (patch)
tree7a7cb84c9b26c591271b9ad8a2a207dfb6abac36 /aoc15
parent6c4f0f57cb50537f21dd121bc0089b4b4fd6a7c4 (diff)
Changed input parsing to decrease number of unwraps
Diffstat (limited to 'aoc15')
-rw-r--r--aoc15/src/main.rs31
1 files changed, 15 insertions, 16 deletions
diff --git a/aoc15/src/main.rs b/aoc15/src/main.rs
index 3db59ea..a7f0f64 100644
--- a/aoc15/src/main.rs
+++ b/aoc15/src/main.rs
@@ -8,29 +8,28 @@ use std::fs::File;
fn main() {
let gears = read_file();
- let pass = (0..).find(|&i| can_pass(&gears, i)).unwrap();
+ let pass = (0..).find(|&i| can_pass(&gears, i)).expect("Reached end of infinite range without finding output");
println!("First pass at t={}", pass);
}
-fn can_pass(gears: &Vec<(i32, i32)>, time: i32) -> bool {
- for i in 0..gears.len() {
- let (gear_pos, gear_size) = gears[i];
- if (gear_pos + time + i as i32 + 1) % gear_size != 0 {
- return false;
- }
- }
- true
+fn can_pass(gears: &Vec<(i32, i32, i32)>, time: i32) -> bool {
+ gears.iter().all(|&(time_offset, init_pos, gear_size)| (init_pos + time_offset + time) % gear_size == 0)
}
-fn read_file() -> Vec<(i32, i32)> {
+fn read_file() -> Vec<(i32, i32, i32)> {
let file = BufReader::new(File::open("input.txt").unwrap());
- let line_regex = Regex::new(r"Disc #\d+ has (\d+) positions; at time=0, it is at position (\d+).").unwrap();
+ let line_regex = Regex::new(r"Disc #(\d+) has (\d+) positions; at time=0, it is at position (\d+).").unwrap();
file.lines()
- .map(|line| line.unwrap().trim().to_string())
- .filter(|line| line.len() > 0)
- .map(|line| {
- let cap = line_regex.captures(line.as_ref()).unwrap();
- (cap.at(2).unwrap().parse().unwrap(), cap.at(1).unwrap().parse().unwrap())
+ .filter_map(|line| {
+ line_regex.captures(line.unwrap().as_ref()).and_then(|cap| {
+ let time_offset = cap.at(1).and_then(|s| s.parse::<i32>().ok());
+ let init_pos = cap.at(3).and_then(|s| s.parse::<i32>().ok());
+ let gear_size = cap.at(2).and_then(|s| s.parse::<i32>().ok());
+ match (time_offset, init_pos, gear_size) {
+ (Some(a), Some(b), Some(c)) => Some((a,b,c)),
+ _ => None
+ }
+ })
})
.collect()
}