diff --git a/src/day01.rs b/src/day01.rs index 0815a9b..75b1a5f 100644 --- a/src/day01.rs +++ b/src/day01.rs @@ -3,7 +3,7 @@ use crate::utils; use anyhow::{anyhow, Result}; -fn day01_part1(data: &[i64]) -> Result { +fn part1(data: &[i64]) -> Result { for c in utils::combinations(2, data.len()) { if data[c[0]] + data[c[1]] == 2020 { return Ok(data[c[0]] * data[c[1]]); @@ -12,7 +12,7 @@ fn day01_part1(data: &[i64]) -> Result { Err(anyhow!("no result found")) } -fn day01_part2(data: &[i64]) -> Result { +fn part2(data: &[i64]) -> Result { for c in utils::combinations(3, data.len()) { if data[c[0]] + data[c[1]] + data[c[2]] == 2020 { return Ok(data[c[0]] * data[c[1]] * data[c[2]]); @@ -25,10 +25,10 @@ pub fn run() -> Result<(i64, i64)> { let data = utils::read_i64s("data/input-01.txt")?; let answers = utils::read_i64s("data/output-01.txt")?; - let p1 = day01_part1(&data)?; + let p1 = part1(&data)?; assert_eq!(p1, answers[0]); - let p2 = day01_part2(&data)?; + let p2 = part2(&data)?; assert_eq!(p2, answers[1]); Ok((p1, p2)) diff --git a/src/utils.rs b/src/utils.rs index 3c20968..d76c5c1 100644 --- a/src/utils.rs +++ b/src/utils.rs @@ -29,6 +29,22 @@ pub struct CombinationsState { done: bool, } +pub fn combinations(t: usize, n: usize) -> CombinationsState { + let mut c = CombinationsState { + t, + c: vec![0; t + 2], + done: false, + }; + + // L1. Initialize + for i in 0..t { + c.c[i] = i; + } + c.c[t] = n; + c.c[t + 1] = 0; + c +} + impl Iterator for CombinationsState { type Item = Vec; @@ -44,7 +60,7 @@ impl Iterator for CombinationsState { let mut j = 0; while (self.c[j] + 1) == self.c[j + 1] { self.c[j] = j; - j = j + 1; + j += 1; } // L4. Done? @@ -53,25 +69,9 @@ impl Iterator for CombinationsState { }; // L5. Increate c[j]. - self.c[j] = self.c[j] + 1; + self.c[j] += 1; // return Some(visited) or None from L2 above ret } } - -pub fn combinations(t: usize, n: usize) -> CombinationsState { - let mut c = CombinationsState { - t: t, - c: vec![0; t + 2], - done: false, - }; - - // L1. Initialize - for i in 0..t { - c.c[i] = i; - } - c.c[t + 0] = n; - c.c[t + 1] = 0; - return c; -}