2020: day01: part 1
This commit is contained in:
parent
fa32903fdc
commit
b44c6bacbc
8 changed files with 318 additions and 1 deletions
56
aoc2020/src/day01.rs
Normal file
56
aoc2020/src/day01.rs
Normal file
|
|
@ -0,0 +1,56 @@
|
|||
use std::fmt::Write;
|
||||
|
||||
use aoc::{err, Result};
|
||||
|
||||
const INPUT: &str = include_str!("../input/day01.txt");
|
||||
|
||||
pub fn run() -> Result<String> {
|
||||
let mut res = String::with_capacity(128);
|
||||
|
||||
writeln!(res, "part 1: {}", part1(INPUT)?)?;
|
||||
|
||||
Ok(res)
|
||||
}
|
||||
|
||||
fn part1(input: &str) -> Result<u64> {
|
||||
let entries = input
|
||||
.lines()
|
||||
.map(|line| line.parse::<u64>().map_err(|e| err!("{}", e)))
|
||||
.collect::<Result<Vec<u64>>>()?;
|
||||
|
||||
let (a, b) = find_2020_sum(&entries)?;
|
||||
|
||||
Ok(a * b)
|
||||
}
|
||||
|
||||
fn find_2020_sum(entries: &[u64]) -> Result<(u64, u64)> {
|
||||
for i in 0..(entries.len()) {
|
||||
for j in 0..entries.len() {
|
||||
if i == j {
|
||||
continue;
|
||||
}
|
||||
if entries[i] + entries[j] == 2020 {
|
||||
return Ok((entries[i], entries[j]));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
Err(err!("couldn't find 2 elements that sum to 2020"))
|
||||
}
|
||||
|
||||
#[cfg(test)]
|
||||
mod tests {
|
||||
use super::*;
|
||||
|
||||
#[test]
|
||||
fn part1_provided() {
|
||||
let (a, b) = find_2020_sum(&vec![1721, 979, 366, 299, 675, 1456]).unwrap();
|
||||
assert_eq!(a, 1721);
|
||||
assert_eq!(b, 299);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn part1_real() {
|
||||
assert_eq!(part1(INPUT).unwrap(), 1014171);
|
||||
}
|
||||
}
|
||||
1
aoc2020/src/lib.rs
Normal file
1
aoc2020/src/lib.rs
Normal file
|
|
@ -0,0 +1 @@
|
|||
pub mod day01;
|
||||
10
aoc2020/src/main.rs
Normal file
10
aoc2020/src/main.rs
Normal file
|
|
@ -0,0 +1,10 @@
|
|||
use aoc::DayFunc;
|
||||
use aoc::Result;
|
||||
|
||||
use aoc2020::day01;
|
||||
|
||||
fn main() -> Result<()> {
|
||||
let days: &[DayFunc] = &[day01::run];
|
||||
|
||||
aoc::run(days)
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue