Use iterators where possible for day 3
This commit is contained in:
parent
9437441dc7
commit
f73964c34e
51
src/day03.rs
51
src/day03.rs
@ -1,4 +1,4 @@
|
||||
use std::collections::{HashMap, HashSet};
|
||||
use std::collections::HashMap;
|
||||
|
||||
use aoc_runner_derive::{aoc, aoc_generator};
|
||||
use nom::{Finish, IResult};
|
||||
@ -15,14 +15,14 @@ fn input_generator(input: &str) -> Vec<String> {
|
||||
|
||||
#[aoc(day3, part1)]
|
||||
fn part1(input: &[String]) -> u32 {
|
||||
let mut symbol_neighbors = HashSet::new();
|
||||
for (row, line) in input.iter().enumerate() {
|
||||
for (col, ch) in line.chars().enumerate() {
|
||||
if !ch.is_ascii_digit() && ch != '.' {
|
||||
symbol_neighbors.extend(GridIndex::new(col, row).neighbors());
|
||||
}
|
||||
}
|
||||
}
|
||||
let symbol_neighbors = input
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(row, line)| {
|
||||
line.match_indices(|ch: char| !ch.is_ascii_digit() && ch != '.')
|
||||
.flat_map(move |(col, _)| GridIndex::new(col, row).neighbors())
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut part_sum = 0;
|
||||
for (row, line) in input.iter().enumerate() {
|
||||
let mut col: usize = 0;
|
||||
@ -32,8 +32,8 @@ fn part1(input: &[String]) -> u32 {
|
||||
let rest = &line[col..];
|
||||
let (rem, num) = parse_num(rest).finish().unwrap();
|
||||
let num_len = rest.len() - rem.len();
|
||||
for i in 0..num_len {
|
||||
if symbol_neighbors.contains(&GridIndex::new(col + i, row)) {
|
||||
for col in col..(col + num_len) {
|
||||
if symbol_neighbors.contains(&GridIndex::new(col, row)) {
|
||||
part_sum += num;
|
||||
break;
|
||||
}
|
||||
@ -49,14 +49,14 @@ fn part1(input: &[String]) -> u32 {
|
||||
|
||||
#[aoc(day3, part2)]
|
||||
fn part2(input: &[String]) -> u32 {
|
||||
let mut gear_locs = Vec::new();
|
||||
for (row, line) in input.iter().enumerate() {
|
||||
for (col, ch) in line.chars().enumerate() {
|
||||
if ch == '*' {
|
||||
gear_locs.push(GridIndex::new(col, row));
|
||||
}
|
||||
}
|
||||
}
|
||||
let gear_locs = input
|
||||
.iter()
|
||||
.enumerate()
|
||||
.flat_map(|(row, line)| {
|
||||
line.match_indices('*')
|
||||
.map(move |(col, _)| GridIndex::new(col, row))
|
||||
})
|
||||
.collect::<Vec<_>>();
|
||||
let mut gear_neighbor_numbers = HashMap::<usize, Vec<u32>>::new();
|
||||
for (row, line) in input.iter().enumerate() {
|
||||
let mut col: usize = 0;
|
||||
@ -81,12 +81,9 @@ fn part2(input: &[String]) -> u32 {
|
||||
}
|
||||
}
|
||||
}
|
||||
let mut gear_ratio_sum = 0;
|
||||
for (_, number_neighbors) in gear_neighbor_numbers.iter() {
|
||||
if number_neighbors.len() != 2 {
|
||||
continue;
|
||||
}
|
||||
gear_ratio_sum += number_neighbors[0] * number_neighbors[1];
|
||||
}
|
||||
gear_ratio_sum
|
||||
gear_neighbor_numbers
|
||||
.values()
|
||||
.filter(|x| x.len() == 2)
|
||||
.map(|x| x[0] * x[1])
|
||||
.sum()
|
||||
}
|
||||
|
Loading…
Reference in New Issue
Block a user