|
| 1 | +// Copyright (c) 2025 Lexi Robinson |
| 2 | +// |
| 3 | +// Licensed under the EUPL, Version 1.2 |
| 4 | +// |
| 5 | +// You may not use this work except in compliance with the Licence. |
| 6 | +// You should have received a copy of the Licence along with this work. If not, see: |
| 7 | +// <https://joinup.ec.europa.eu/collection/eupl/eupl-text-eupl-12>. |
| 8 | +// See the Licence for the specific language governing permissions and limitations under the Licence. |
| 9 | + |
| 10 | +use std::ops::RangeInclusive; |
| 11 | + |
| 12 | +use itertools::Itertools; |
| 13 | +use num::Integer; |
| 14 | + |
| 15 | +use crate::AoCError; |
| 16 | + |
| 17 | +pub fn part_1(data: crate::DataIn) -> crate::AoCResult<String> { |
| 18 | + // damn references |
| 19 | + let lines = data.collect_vec(); |
| 20 | + let ranges: Vec<RangeInclusive<u64>> = lines |
| 21 | + .iter() |
| 22 | + .flat_map(|line| line.split(',')) |
| 23 | + .map(|raw| { |
| 24 | + raw.split_once('-') |
| 25 | + .ok_or_else(|| AoCError::new(format!("Line {raw} is missing a -!"))) |
| 26 | + .and_then(|(start, end)| Ok((start.parse()?)..=(end.parse()?))) |
| 27 | + }) |
| 28 | + .try_collect()?; |
| 29 | + |
| 30 | + log::debug!("Collected ranges: {ranges:?}"); |
| 31 | + |
| 32 | + let ret: u64 = ranges |
| 33 | + .into_iter() |
| 34 | + .flat_map(|range| { |
| 35 | + range.filter(|num| { |
| 36 | + let numstr = num.to_string(); |
| 37 | + // all invalid ids are a pair of numbers, so they must be even |
| 38 | + if numstr.len().is_odd() { |
| 39 | + return false; |
| 40 | + } |
| 41 | + // safety: this string is made of numbers which are all going to be ascii |
| 42 | + // characters unless something has gone catastrophically wrong |
| 43 | + let (start, end) = numstr.split_at(numstr.len() / 2); |
| 44 | + start == end |
| 45 | + }) |
| 46 | + }) |
| 47 | + .inspect(|serial| log::debug!("Found invalid serial number {serial}")) |
| 48 | + .sum(); |
| 49 | + |
| 50 | + Ok(ret.to_string()) |
| 51 | +} |
| 52 | + |
| 53 | +inventory::submit!(crate::AoCDay { |
| 54 | + year: "2025", |
| 55 | + day: "2", |
| 56 | + part_1: crate::AoCPart { |
| 57 | + main: part_1, |
| 58 | + example: part_1 |
| 59 | + }, |
| 60 | + part_2: None |
| 61 | +}); |
0 commit comments