summary refs log tree commit diff
path: root/18/src
diff options
context:
space:
mode:
Diffstat (limited to '18/src')
-rw-r--r--18/src/expression.lalrpop54
-rw-r--r--18/src/main.rs39
2 files changed, 93 insertions, 0 deletions
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 = {
+  <Term>,
+  <left:Expression> PLUS <right:Term> => {
+    left + right
+  },
+  <left:Expression> STAR <right:Term> => {
+    left * right
+  },
+};
+
+Term: i64 = {
+  NUMBER => {
+    <>.parse::<i64>().unwrap()
+  },
+  LEFT_PARENTHESIS <Expression> RIGHT_PARENTHESIS,
+};
+
+pub ExpressionPro: i64 = {
+  <Expression2Pro>,
+  <left:ExpressionPro> STAR <right:Expression2Pro> => {
+    left * right
+  },
+};
+
+Expression2Pro: i64 = {
+  <TermPro>,
+  <left:Expression2Pro> PLUS <right:TermPro> => {
+    left + right
+  },
+};
+
+TermPro: i64 = {
+  NUMBER => {
+    <>.parse::<i64>().unwrap()
+  },
+  LEFT_PARENTHESIS <ExpressionPro> 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(())
+}