Refactor Solver trait to streamline usage
This commit is contained in:
+12
-33
@@ -1,35 +1,19 @@
|
||||
use crate::common::interval::Interval;
|
||||
use crate::solvers::Solver;
|
||||
use std::collections::BTreeSet;
|
||||
use std::fs::File;
|
||||
use std::io;
|
||||
use std::io::BufRead;
|
||||
|
||||
pub struct Cafeteria {
|
||||
part1: u64,
|
||||
part2: u64,
|
||||
}
|
||||
pub struct Cafeteria {}
|
||||
|
||||
impl Solver for Cafeteria {
|
||||
fn get_puzzle_index(&self) -> u8 {
|
||||
5
|
||||
}
|
||||
fn get_puzzle_name(&self) -> &str {
|
||||
"Cafeteria"
|
||||
}
|
||||
fn get_input_filename(&self) -> &str {
|
||||
"cafeteria.txt"
|
||||
}
|
||||
fn get_part1(&self) -> u64 {
|
||||
self.part1
|
||||
}
|
||||
fn get_part2(&self) -> u64 {
|
||||
self.part2
|
||||
}
|
||||
fn process_data(&mut self, mut lines: io::Lines<io::BufReader<File>>) {
|
||||
const PUZZLE_INDEX: u8 = 5;
|
||||
const PUZZLE_NAME: &'static str = "Cafeteria";
|
||||
const INPUT_FILENAME: &'static str = "cafeteria.txt";
|
||||
|
||||
fn process_data<R: BufRead>(&self, mut reader: R) -> (u64, u64) {
|
||||
// Builds intervals collection.
|
||||
let mut intervals: BTreeSet<Interval> = BTreeSet::new();
|
||||
for line in lines
|
||||
.by_ref()
|
||||
for line in reader.by_ref().lines()
|
||||
.map_while(|x| x.ok().filter(|s| !s.is_empty()))
|
||||
{
|
||||
let values: Vec<u64> = line.split('-').map_while(|s| s.parse().ok()).collect();
|
||||
@@ -68,19 +52,14 @@ impl Solver for Cafeteria {
|
||||
}
|
||||
}
|
||||
|
||||
let mut part1 = 0;
|
||||
// Tests values against intervals.
|
||||
for value in lines.map_while(|x| x.ok()?.parse::<u64>().ok()) {
|
||||
for value in reader.lines().map_while(|x| x.ok()?.parse::<u64>().ok()) {
|
||||
if intervals.iter().any(|interval| interval.contains(value)) {
|
||||
self.part1 += 1;
|
||||
part1 += 1;
|
||||
}
|
||||
}
|
||||
|
||||
self.part2 = intervals.iter().map(|x| x.len()).sum();
|
||||
}
|
||||
}
|
||||
|
||||
impl Cafeteria {
|
||||
pub fn new() -> Cafeteria {
|
||||
Cafeteria { part1: 0, part2: 0 }
|
||||
(part1, intervals.iter().map(|x| x.len()).sum())
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user