misc cleanup, minor readability fix, cargo clippy

This commit is contained in:
Stephen Waits committed 2020-12-02 22:22:55 -08:00
1 parent b217f3a5dd
commit 86ac6625de
2 files changed
+22 -22

No files matched your search

+4 -4
View File
@@ -3,7 +3,7 @@
use crate::utils; use crate::utils;
use anyhow::{anyhow, Result}; use anyhow::{anyhow, Result};
fn day01_part1(data: &[i64]) -> Result<i64> { fn part1(data: &[i64]) -> Result<i64> {
for c in utils::combinations(2, data.len()) { for c in utils::combinations(2, data.len()) {
if data[c[0]] + data[c[1]] == 2020 { if data[c[0]] + data[c[1]] == 2020 {
return Ok(data[c[0]] * data[c[1]]); return Ok(data[c[0]] * data[c[1]]);
@@ -12,7 +12,7 @@ fn day01_part1(data: &[i64]) -> Result<i64> {
Err(anyhow!("no result found")) Err(anyhow!("no result found"))
} }
fn day01_part2(data: &[i64]) -> Result<i64> { fn part2(data: &[i64]) -> Result<i64> {
for c in utils::combinations(3, data.len()) { for c in utils::combinations(3, data.len()) {
if data[c[0]] + data[c[1]] + data[c[2]] == 2020 { if data[c[0]] + data[c[1]] + data[c[2]] == 2020 {
return Ok(data[c[0]] * data[c[1]] * data[c[2]]); 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 data = utils::read_i64s("data/input-01.txt")?;
let answers = utils::read_i64s("data/output-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]); assert_eq!(p1, answers[0]);
let p2 = day01_part2(&data)?; let p2 = part2(&data)?;
assert_eq!(p2, answers[1]); assert_eq!(p2, answers[1]);
Ok((p1, p2)) Ok((p1, p2))
+18 -18
View File
@@ -29,6 +29,22 @@ pub struct CombinationsState {
done: bool, 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 { impl Iterator for CombinationsState {
type Item = Vec<usize>; type Item = Vec<usize>;
@@ -44,7 +60,7 @@ impl Iterator for CombinationsState {
let mut j = 0; let mut j = 0;
while (self.c[j] + 1) == self.c[j + 1] { while (self.c[j] + 1) == self.c[j + 1] {
self.c[j] = j; self.c[j] = j;
j = j + 1; j += 1;
} }
// L4. Done? // L4. Done?
@@ -53,25 +69,9 @@ impl Iterator for CombinationsState {
}; };
// L5. Increate c[j]. // L5. Increate c[j].
self.c[j] = self.c[j] + 1; self.c[j] += 1;
// return Some(visited) or None from L2 above // return Some(visited) or None from L2 above
ret 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;
}