main.rs (3194B)
1 use std::collections::HashSet; 2 3 #[derive(Debug, Copy, Clone)] 4 enum FoldInstruction { 5 X(i32), 6 Y(i32), 7 } 8 9 impl FoldInstruction { 10 fn new(s: &str) -> FoldInstruction { 11 let mut it = s.split("="); 12 let axis = it.next().unwrap(); 13 let coord = it.next().unwrap().parse::<i32>().unwrap(); 14 match axis.chars().last() { 15 Some('x') => FoldInstruction::X(coord), 16 Some('y') => FoldInstruction::Y(coord), 17 _ => unreachable!(), 18 } 19 } 20 21 fn fold(&self, paper: &HashSet<(i32, i32)>) -> HashSet<(i32, i32)> { 22 let mut folded_paper = HashSet::new(); 23 for (x, y) in paper { 24 match self { 25 Self::X(x_fold) => match x.cmp(x_fold) { 26 std::cmp::Ordering::Less => { 27 folded_paper.insert((*x, *y)); 28 } 29 std::cmp::Ordering::Greater => { 30 folded_paper.insert((x_fold - (*x - x_fold), *y)); 31 } 32 // folded axis is discarded 33 std::cmp::Ordering::Equal => (), 34 }, 35 Self::Y(y_fold) => match y.cmp(y_fold) { 36 std::cmp::Ordering::Less => { 37 folded_paper.insert((*x, *y)); 38 } 39 std::cmp::Ordering::Greater => { 40 folded_paper.insert((*x, y_fold - (*y - y_fold))); 41 } 42 std::cmp::Ordering::Equal => (), 43 }, 44 } 45 } 46 folded_paper 47 } 48 } 49 50 fn main() { 51 let input = std::fs::read_to_string("input.txt") 52 .unwrap() 53 .trim() 54 .split('\n') 55 .map(|s| s.to_string()) 56 .collect::<Vec<String>>(); 57 let split = input.iter().position(|s| s == "").unwrap(); 58 let paper = input[..split] 59 .iter() 60 .map(|s| { 61 let mut it = s.split(","); 62 ( 63 it.next().unwrap().parse::<i32>().unwrap(), 64 it.next().unwrap().parse::<i32>().unwrap(), 65 ) 66 }) 67 .collect::<HashSet<_>>(); 68 let fold_instructions = input[(split + 1)..] 69 .iter() 70 .map(|s| FoldInstruction::new(s)) 71 .collect::<Vec<_>>(); 72 // 842 73 println!("Part 1: {}", part_1(&paper, &fold_instructions)); 74 // BFKRCJZU 75 println!("Part 2:"); 76 part_2(&paper, &fold_instructions); 77 } 78 79 fn part_1(paper: &HashSet<(i32, i32)>, fold_instructions: &Vec<FoldInstruction>) -> usize { 80 fold_instructions[0].fold(paper).len() 81 } 82 83 fn plot(paper: &HashSet<(i32, i32)>) { 84 let x_max = *paper.iter().map(|(x, _)| x).max().unwrap(); 85 let y_max = *paper.iter().map(|(_, y)| y).max().unwrap(); 86 // need to flip x and y for letters to show up 87 for y in 0..=y_max { 88 for x in 0..=x_max { 89 print!("{}", if paper.contains(&(x, y)) { '#' } else { '.' }); 90 } 91 println!(); 92 } 93 } 94 95 fn part_2(paper: &HashSet<(i32, i32)>, fold_instructions: &Vec<FoldInstruction>) { 96 let mut folded_paper = paper.clone(); 97 for fi in fold_instructions { 98 folded_paper = fi.fold(&folded_paper); 99 } 100 plot(&folded_paper); 101 }