day 13 part 2

This commit is contained in:
Andy Teijelo 2023-12-15 23:26:08 -05:00
parent 50f217eea0
commit df59ba47a8

View file

@ -1,68 +1,54 @@
use std::{collections::HashSet, io::stdin, vec};
use anyhow::Result;
fn mirror_points(line: &[char]) -> Vec<usize> {
let mut result = vec![];
for i in 1..line.len() {
let mut mirror = true;
for j in 0..i {
if i + j >= line.len() {
continue;
}
if line[i - j - 1] != line[i + j] {
mirror = false;
}
}
if mirror {
result.push(i);
}
}
result
}
fn vertical_mirror_points(grid: &Vec<Vec<char>>) -> HashSet<usize> {
let mut s: HashSet<usize> = HashSet::new();
for row in grid {
let n: HashSet<usize> = mirror_points(row).iter().copied().collect();
if s.is_empty() {
s = n;
} else {
s = s.intersection(&n).cloned().collect();
if s.is_empty() {
return s;
}
}
}
s
}
fn horizontal_mirror_points(grid: &Vec<Vec<char>>) -> HashSet<usize> {
let mut s: HashSet<usize> = HashSet::new();
for x in 0..grid[0].len() {
let mut column = vec![];
for row in grid {
column.push(row[x]);
}
let n: HashSet<usize> = mirror_points(&column).iter().copied().collect();
if s.is_empty() {
s = n;
} else {
s = s.intersection(&n).cloned().collect();
if s.is_empty() {
return s;
}
}
}
s
}
use std::{collections::HashSet, io::stdin, vec};
type Grid = Vec<Vec<char>>;
fn vertical_mirror_points(grid: &Grid) -> HashSet<usize> {
let mut s = HashSet::new();
for x in 1..grid[0].len() {
let mut differences = 0;
for row in grid {
for i in 0..x {
if x + i >= row.len() {
continue;
}
if row[x - i - 1] != row[x + i] {
differences += 1;
}
}
}
if differences == 1 {
s.insert(x);
}
}
s
}
fn horizontal_mirror_points(grid: &Grid) -> HashSet<usize> {
let mut s = HashSet::new();
for y in 1..grid.len() {
let mut differences = 0;
for x in 0..grid[0].len() {
for i in 0..y {
if y + i >= grid.len() {
continue;
}
if grid[y - i - 1][x] != grid[y + i][x] {
differences += 1;
}
}
}
if differences == 1 {
s.insert(y);
}
}
s
}
fn main() -> Result<()> {
let mut grids: Vec<Grid> = vec![];
grids.push(vec![]);
for line in stdin().lines().map_while(Result::ok) {
println!("{line}");
if line.is_empty() {
grids.push(vec![]);
continue;
@ -85,16 +71,4 @@ fn main() -> Result<()> {
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn test_mirror_points() {
let chars: Vec<char> = "#.##..##.".chars().collect();
assert_eq!(mirror_points(&chars), vec![5, 7]);
let chars: Vec<char> = "#.##..#".chars().collect();
assert_eq!(mirror_points(&chars), vec![5]);
let chars: Vec<char> = ".#.##".chars().collect();
assert_eq!(mirror_points(&chars), vec![4]);
}
}
mod tests {}