Part 2 done
This commit is contained in:
parent
07e84ae119
commit
78b20ae784
3 changed files with 43 additions and 0 deletions
BIN
day_1/part2
Executable file
BIN
day_1/part2
Executable file
Binary file not shown.
43
day_1/part2.rs
Normal file
43
day_1/part2.rs
Normal file
|
@ -0,0 +1,43 @@
|
|||
use std::fs::File;
|
||||
use std::io::{self, BufRead};
|
||||
use std::path::Path;
|
||||
use std::collections::HashMap;
|
||||
use std::env;
|
||||
|
||||
fn read_lines<P>(filename: P) -> io::Result<io::Lines<io::BufReader<File>>>
|
||||
where P: AsRef<Path>, {
|
||||
let file = File::open(filename)?;
|
||||
Ok(io::BufReader::new(file).lines())
|
||||
}
|
||||
|
||||
fn main() {
|
||||
let mut occurrences: HashMap<i32, i32> = HashMap::new();
|
||||
let mut left_list: Vec<i32> = vec![];
|
||||
let mut right_list: Vec<i32> = vec![];
|
||||
|
||||
let args: Vec<_> = env::args().collect();
|
||||
|
||||
if let Ok(lines) = read_lines(args[1].clone()) {
|
||||
for line in lines.flatten() {
|
||||
let parts = line.split(" ").collect::<Vec<_>>();
|
||||
let lnum = parts[0].parse::<i32>().unwrap();
|
||||
let rnum = parts[1].parse::<i32>().unwrap();
|
||||
left_list.push(lnum);
|
||||
right_list.push(rnum);
|
||||
}
|
||||
for left_n in left_list {
|
||||
let entry = occurrences.entry(left_n).or_insert(0);
|
||||
for right_n in &right_list {
|
||||
if left_n == *right_n {
|
||||
*entry += 1;
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
let mut sum = 0;
|
||||
for (num, count) in &occurrences {
|
||||
sum += num * count;
|
||||
}
|
||||
println!("{}", sum)
|
||||
}
|
||||
}
|
Loading…
Reference in a new issue