day 18 data parsing
This commit is contained in:
parent
5abd82efff
commit
63818ee2ee
72
2021/src/day18.rs
Normal file
72
2021/src/day18.rs
Normal file
@ -0,0 +1,72 @@
|
||||
// use std::iter::Peekable;
|
||||
use std::str::Chars;
|
||||
|
||||
use color_eyre::eyre;
|
||||
use eyre::eyre;
|
||||
|
||||
|
||||
#[derive(Debug)]
|
||||
enum Item {
|
||||
Value(u8),
|
||||
SubPair(Box<Pair>),
|
||||
}
|
||||
|
||||
#[derive(Debug)]
|
||||
struct Pair {
|
||||
left: Item,
|
||||
right: Item,
|
||||
}
|
||||
|
||||
|
||||
struct Parser<'a> {
|
||||
chars: Chars<'a>,
|
||||
}
|
||||
|
||||
impl<'a> Parser<'a> {
|
||||
fn from(src: &'a str) -> Parser<'a> {
|
||||
let mut chars = src.chars();
|
||||
chars.next(); // throw away the opening bracket
|
||||
Parser {chars}
|
||||
}
|
||||
|
||||
fn parse(&mut self) -> eyre::Result<Pair> {
|
||||
let mut items = Vec::with_capacity(2);
|
||||
while items.len() < 2 {
|
||||
let item = match self.chars.next() {
|
||||
Some('[') => Item::SubPair(Box::new(self.parse()?)),
|
||||
Some(','|']') => {continue;},
|
||||
Some(c) => Item::Value(c.to_digit(10).unwrap() as u8),
|
||||
None => {return Err(eyre!("Ran out of characters to parse"));},
|
||||
};
|
||||
items.push(item);
|
||||
}
|
||||
|
||||
let right = items.pop().unwrap();
|
||||
let left = items.pop().unwrap();
|
||||
Ok(Pair {left, right})
|
||||
}
|
||||
}
|
||||
|
||||
|
||||
fn load(data: &str) -> eyre::Result<Vec<Pair>>{
|
||||
let mut pairs = Vec::new();
|
||||
for line in data.lines() {
|
||||
let mut parser = Parser::from(line);
|
||||
match parser.parse() {
|
||||
Ok(pair) => pairs.push(pair),
|
||||
Err(e) => return Err(eyre!("Invalid input: {}", line)),
|
||||
}
|
||||
}
|
||||
Ok(pairs)
|
||||
}
|
||||
|
||||
|
||||
const _SAMPLE: &str = "[[1,9],[8,5]]";
|
||||
|
||||
pub fn run(data: &str) -> eyre::Result<(usize, usize)> {
|
||||
let pairs = load(data)?;
|
||||
dbg!(pairs.len());
|
||||
dbg!(&pairs[0]);
|
||||
|
||||
Ok((0, 0))
|
||||
}
|
@ -4,14 +4,14 @@ use color_eyre::eyre;
|
||||
|
||||
mod lib;
|
||||
use lib::load;
|
||||
mod day17;
|
||||
mod day18;
|
||||
|
||||
|
||||
fn main() -> eyre::Result<()> {
|
||||
let data = load("data/17.txt")?;
|
||||
let data = load("data/18.txt")?;
|
||||
|
||||
let start = Instant::now();
|
||||
let (one, two) = day17::run(&data)?;
|
||||
let (one, two) = day18::run(&data)?;
|
||||
let (dur, unit) = format_ns(start.elapsed().as_nanos());
|
||||
|
||||
let precision = 2.0 - dur.log10().floor();
|
||||
|
Loading…
x
Reference in New Issue
Block a user