Solved day1

This commit is contained in:
2020-12-01 09:24:27 +01:00
commit 62cd585261
4 changed files with 309 additions and 0 deletions

90
src/day1.rs Normal file
View File

@@ -0,0 +1,90 @@
use super::util;
pub fn solve() {
let lines = util::read_file("input/day1.txt");
let mut nums: Vec<u32> = lines.iter().map(|s|s.parse::<u32>().unwrap()).collect();
nums.sort();
let part1 = find_pairs_summing_to(&nums, 2020);
println!("Day 1 Part 1: {}", part1.0 * part1.1);
let part2 = find_triplet_summing_to(&nums, 2020);
println!("Day 1 Part 2: {}", part2.0 * part2.1 * part2.2);
}
fn find_pairs_summing_to(nums: &Vec<u32>, target: u32) -> (u32, u32) {
let mut i:usize = 0;
let mut j:usize = nums.len() - 1;
loop {
if j < i {
panic!("Couldn't find match");
}
let sum = nums[i] + nums[j];
if sum < target {
i += 1;
} else if sum > target {
j -= 1;
} else {
return (nums[i], nums[j]);
}
}
}
fn find_triplet_summing_to(nums: &Vec<u32>, target: u32) -> (u32, u32, u32){
for i in 0..nums.len() {
for j in (0..nums.len()).rev() {
if j <= i {
break;
}
let n1 = nums[i];
let n2 = nums[j];
if target < n1 + n2 {
continue;
}
let n3_target = target - n1 - n2;
let res = nums.binary_search(&n3_target);
if res.is_ok() && res.unwrap() > i && res.unwrap() < j {
return (n1, n2, n3_target);
}
}
}
panic!("Couldn't find match!");
//
// let mut i:usize = 0;
// let mut j:usize = nums.len() - 1;
// loop {
// if j < i {
//
// // Reset with i one higher:
// i += 1;
// j = nums.len() - 1;
// }
//
// let n1 = nums[i];
// let n2 = nums[j];
// let sum = n1 + n2;
// if sum + n1 > target {
// j -= 1;
// } else {
// // See if we can find a third number between i and j that makes the sum equal to the target
// let n3_target = target - sum;
// let res = nums.binary_search(&n3_target);
// if res.is_ok() {
// // Found it!
// return (n1, n2, n3_target)
// } else {
// j -= 1;
// }
// }
// }
}

13
src/util.rs Normal file
View File

@@ -0,0 +1,13 @@
use std::fs;
pub fn read_file(filename: &str) -> Vec<String> {
let contents = fs::read_to_string(filename)
.expect("Couldn't read file!");
let mut res: Vec<String> = Vec::new();
contents.lines().for_each(|l| res.push(String::from(l)));
res
}