From b228e7f80adb00ae4c73c855155e7ec4287ab5d6 Mon Sep 17 00:00:00 2001 From: Glenn Griffin Date: Wed, 2 Dec 2020 21:06:48 -0800 Subject: [PATCH] alternative --- src/bin/1.rs | 84 ++++++++++++++++++++++++++++++---------------------- 1 file changed, 49 insertions(+), 35 deletions(-) diff --git a/src/bin/1.rs b/src/bin/1.rs index 0b07b10..ec86b89 100644 --- a/src/bin/1.rs +++ b/src/bin/1.rs @@ -36,51 +36,65 @@ Of course, your expense report is much larger. Find the two entries that sum to do you get if you multiply them together? */ -use std::fs::{File}; -use std::collections::HashSet; -use std::io::{BufRead, BufReader}; use anyhow::Result; +use std::collections::HashSet; +use std::fs::File; +use std::io::{BufRead, BufReader}; -fn find_triple(target: i32, list: &Vec, set: &HashSet) -> i32 { - for i in list { - let product = find_pair(target - i, list, set); - if product > 0 { - return product * i; - } - } - 0 +struct Entries { + list: Vec, + set: HashSet, } -fn find_pair(target: i32, list: &Vec, set: &HashSet) -> i32 { - for i in list { - if i > &target { - break - } - let val = target - i; - if set.contains(&val) { - return i * val; +impl Entries { + fn find_triple(&self, target: i32) -> i32 { + for i in self.list.iter().copied() { + let product = self.find_pair(target - i); + if product > 0 { + return product * i; + } } + 0 + } + + fn find_pair(&self, target: i32) -> i32 { + for i in self.list.iter().copied() { + if i > target { + break; + } + let val = target - i; + if self.set.contains(&val) { + return i * val; + } + } + 0 + } +} + +impl std::iter::FromIterator for Entries { + fn from_iter(iter: T) -> Self + where + T: IntoIterator, + { + let mut list = Vec::new(); + let mut set = HashSet::new(); + for value in iter { + list.push(value); + set.insert(value); + } + list.sort(); + Entries { list, set } } - 0 } fn main() -> Result<()> { //let contents = fs::read_to_string("1.input").expect("Couldn't read \"1.input\""); - let file = File::open("1.input")?; - let reader = BufReader::new(file); + let entries: Entries = BufReader::new(File::open("1.input")?) + .lines() + .filter_map(|line| line.ok()?.parse().ok()) + .collect(); - let mut list: Vec = Vec::new(); - let mut set: HashSet = HashSet::new(); - - for line in reader.lines() { - let value = line?.parse::()?; - list.push(value); - set.insert(value); - } - - list.sort(); - - println!("Pair is {}", find_pair(2020, &list, &set)); - println!("Triple is {}", find_triple(2020, &list, &set)); + println!("Pair is {}", entries.find_pair(2020)); + println!("Triple is {}", entries.find_triple(2020)); Ok(()) }