From 781e65e5a4444800982da71d97cb6b05d7dca17e Mon Sep 17 00:00:00 2001 From: Irene Knapp Date: Thu, 17 Dec 2020 21:56:07 -0800 Subject: 18 --- 18/src/expression.lalrpop | 54 +++++++++++++++++++++++++++++++++++++++++++++++ 18/src/main.rs | 39 ++++++++++++++++++++++++++++++++++ 2 files changed, 93 insertions(+) create mode 100644 18/src/expression.lalrpop create mode 100644 18/src/main.rs (limited to '18/src') diff --git a/18/src/expression.lalrpop b/18/src/expression.lalrpop new file mode 100644 index 0000000..222a7e6 --- /dev/null +++ b/18/src/expression.lalrpop @@ -0,0 +1,54 @@ +grammar; + +pub Expression: i64 = { + , + PLUS => { + left + right + }, + STAR => { + left * right + }, +}; + +Term: i64 = { + NUMBER => { + <>.parse::().unwrap() + }, + LEFT_PARENTHESIS RIGHT_PARENTHESIS, +}; + +pub ExpressionPro: i64 = { + , + STAR => { + left * right + }, +}; + +Expression2Pro: i64 = { + , + PLUS => { + left + right + }, +}; + +TermPro: i64 = { + NUMBER => { + <>.parse::().unwrap() + }, + LEFT_PARENTHESIS RIGHT_PARENTHESIS, +}; + +match { + r"\p{Zs}+" => { }, + + r"[0-9]+" => NUMBER, + + "+" => PLUS, + + "*" => STAR, + + "(" => LEFT_PARENTHESIS, + + ")" => RIGHT_PARENTHESIS, +} + diff --git a/18/src/main.rs b/18/src/main.rs new file mode 100644 index 0000000..53554a2 --- /dev/null +++ b/18/src/main.rs @@ -0,0 +1,39 @@ +use advent_lib::prelude::*; + +//use std::convert::TryFrom; + +#[macro_use] extern crate lalrpop_util; + +lalrpop_mod!(pub expression); + + + +fn main() -> Result<()> { + let mut args = std::env::args(); + if args.len() != 2 { + eprintln!("Usage: advent input"); + } + let _ = args.next(); + let filename = args.next().unwrap(); + + let input = advent_lib::read_lines_file(&filename)?; + + let parser = expression::ExpressionParser::new(); + let parser_pro = expression::ExpressionProParser::new(); + + let mut sum = 0; + let mut sum_pro = 0; + + for line in &input { + let value = parser.parse(line)?; + sum += value; + + let value_pro = parser_pro.parse(line)?; + sum_pro += value_pro; + } + + println!("{}", sum); + println!("{}", sum_pro); + + Ok(()) +} -- cgit 1.4.1