Skip to content

Commit 9715fe3

Browse files
committed
2018 day 2
1 parent 14f6920 commit 9715fe3

File tree

3 files changed

+75
-0
lines changed

3 files changed

+75
-0
lines changed

crates/utils/src/array.rs

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -159,6 +159,25 @@ impl<T, const N: usize> ArrayVec<T, N> {
159159
pub fn is_full(&self) -> bool {
160160
self.len == N
161161
}
162+
163+
/// Returns the backing array.
164+
///
165+
/// Any items after the current length will be set to the default value.
166+
///
167+
/// # Examples
168+
/// ```
169+
/// # use utils::array::ArrayVec;
170+
/// let mut vec: ArrayVec<i32, 5> = ArrayVec::new();
171+
/// vec.push(1).unwrap();
172+
/// vec.push(2).unwrap();
173+
/// vec.push(3).unwrap();
174+
/// vec.pop().unwrap();
175+
/// assert_eq!(vec.into_array(), [1, 2, 0, 0, 0]);
176+
/// ```
177+
#[inline]
178+
pub fn into_array(self) -> [T; N] {
179+
self.data
180+
}
162181
}
163182

164183
impl<T, const N: usize> Deref for ArrayVec<T, N> {

crates/year2018/src/day02.rs

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,55 @@
1+
use std::collections::HashSet;
2+
use utils::array::ArrayVec;
3+
use utils::prelude::*;
4+
5+
/// Finding near-match IDs.
6+
#[derive(Clone, Debug)]
7+
pub struct Day02 {
8+
ids: Vec<ArrayVec<u8, 32>>,
9+
}
10+
11+
impl Day02 {
12+
pub fn new(input: &str, _: InputType) -> Result<Self, InputError> {
13+
Ok(Self {
14+
ids: parser::byte_range(b'a'..=b'z')
15+
.repeat_arrayvec(parser::noop(), 1)
16+
.parse_lines(input)?,
17+
})
18+
}
19+
20+
#[must_use]
21+
#[expect(clippy::manual_contains, reason = ".iter().any() is faster here")]
22+
pub fn part1(&self) -> u32 {
23+
let mut twos = 0;
24+
let mut threes = 0;
25+
for id in &self.ids {
26+
let mut freq = [0u8; 26];
27+
for &i in id {
28+
freq[(i - b'a') as usize] += 1;
29+
}
30+
twos += u32::from(freq.iter().any(|&x| x == 2));
31+
threes += u32::from(freq.iter().any(|&x| x == 3));
32+
}
33+
twos * threes
34+
}
35+
36+
#[must_use]
37+
pub fn part2(&self) -> String {
38+
let mut seen = HashSet::with_capacity(self.ids.len());
39+
for column in 0..self.ids[0].capacity() {
40+
for mut id in self.ids.iter().map(|id| id.clone().into_array()) {
41+
id[column] = 0;
42+
if !seen.insert(id) {
43+
return id.iter().filter(|&&x| x != 0).map(|&x| x as char).collect();
44+
}
45+
}
46+
seen.clear();
47+
}
48+
panic!("no solution found")
49+
}
50+
}
51+
52+
examples!(Day02 -> (u32, &'static str) [
53+
{input: "abcdef\nbababc\nabbcde\nabcccd\naabcdd\nabcdee\nababab", part1: 12},
54+
{input: "abcde\nfghij\nklmno\npqrst\nfguij\naxcye\nwvxyz", part2: "fgij"},
55+
]);

crates/year2018/src/lib.rs

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -3,4 +3,5 @@
33

44
utils::year!(2018 => year2018, ${
55
1 => day01::Day01,
6+
2 => day02::Day02,
67
});

0 commit comments

Comments
 (0)