Day 13, puzzle 2

This commit is contained in:
jazzpi 2022-12-16 01:13:35 +01:00
parent 57f4bc2732
commit f10e8a4c04
2 changed files with 43 additions and 15 deletions

24
src/bin/d13p2.rs Normal file
View File

@ -0,0 +1,24 @@
use aoc22::{
day13::{self, Node},
util,
};
use itertools::Itertools;
pub fn main() {
let mut pairs = day13::parse_pairs(&util::parse_input());
let mut packets = Vec::new();
while let Some(pair) = pairs.pop() {
packets.push(pair.0);
packets.push(pair.1);
}
let div1 = Node::List(vec![Node::List(vec![Node::Num(2)])]);
let div2 = Node::List(vec![Node::List(vec![Node::Num(6)])]);
packets.push(div1.clone());
packets.push(div2.clone());
packets.sort();
let n1 = packets.iter().find_position(|p| **p == div1).unwrap().0 + 1;
let n2 = packets.iter().find_position(|p| **p == div2).unwrap().0 + 1;
println!("Decoder key: {}", n1 * n2);
}

View File

@ -2,52 +2,56 @@ use std::cmp::Ordering;
use itertools::{EitherOrBoth, Itertools};
#[derive(Debug)]
#[derive(Debug, Clone)]
pub enum Node {
List(Vec<Node>),
Num(usize),
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
impl Ord for Node {
fn cmp(&self, other: &Self) -> Ordering {
match self {
Node::List(l1) => match other {
Node::Num(n2) => self.partial_cmp(&Node::List(vec![Node::Num(*n2)])),
Node::Num(n2) => self.cmp(&Node::List(vec![Node::Num(*n2)])),
Node::List(l2) => {
for pair in l1.iter().zip_longest(l2.iter()) {
match pair {
EitherOrBoth::Both(n1, n2) => {
if n1 < n2 {
return Some(Ordering::Less);
return Ordering::Less;
} else if n2 < n1 {
return Some(Ordering::Greater);
return Ordering::Greater;
}
}
EitherOrBoth::Left(_) => return Some(Ordering::Greater),
EitherOrBoth::Right(_) => return Some(Ordering::Less),
EitherOrBoth::Left(_) => return Ordering::Greater,
EitherOrBoth::Right(_) => return Ordering::Less,
}
}
Some(Ordering::Equal)
Ordering::Equal
}
},
Node::Num(n1) => match other {
Node::Num(n2) => n1.partial_cmp(n2),
Node::List(_) => Node::List(vec![Node::Num(*n1)]).partial_cmp(other),
Node::Num(n2) => n1.cmp(n2),
Node::List(_) => Node::List(vec![Node::Num(*n1)]).cmp(other),
},
}
}
}
impl PartialOrd for Node {
fn partial_cmp(&self, other: &Self) -> Option<Ordering> {
Some(self.cmp(other))
}
}
impl PartialEq for Node {
fn eq(&self, other: &Self) -> bool {
self.partial_cmp(other) == Some(Ordering::Equal)
}
fn ne(&self, other: &Self) -> bool {
!self.eq(other)
}
}
impl Eq for Node {}
pub fn parse_pairs(input: &String) -> Vec<(Node, Node)> {
let mut result = Vec::new();