Solution for day 18

main
Inga 🏳‍🌈 4 years ago
parent 4d3ecc4bd9
commit e88318f104
  1. 11
      day18-hard/Cargo.toml
  2. 31
      day18-hard/src/main.rs
  3. 11
      day18/Cargo.toml
  4. 29
      day18/src/main.rs

@ -0,0 +1,11 @@
[package]
name = "day18-hard"
version = "0.1.0"
authors = ["inga-lovinde <52715130+inga-lovinde@users.noreply.github.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nom = "^4.2.3"
nom-peg = "0.1.1"

@ -0,0 +1,31 @@
use std::io::{self, BufRead};
#[macro_use]
extern crate nom;
extern crate nom_peg;
use nom_peg::grammar;
fn main() {
let arithmetic = grammar! {
parse: i64 = <expr> "="
expr: i64 = <l: sum> (" ")* "*" (" ")* <r: expr> => { l * r }
| sum
sum: i64 = <l: value> (" ")* "+" (" ")* <r: sum> => { l + r }
| value
value: i64 = ("0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9")+ => { result.join("").parse::<i64>().unwrap() }
| "(" <expr> ")"
};
let mut result = 0;
let stdin = io::stdin();
for line in stdin.lock().lines() {
let value = arithmetic.parse(&(line.unwrap() + "=")).unwrap().1;
println!("{}", value);
result += value;
}
println!("{}", result)
}

@ -0,0 +1,11 @@
[package]
name = "day18"
version = "0.1.0"
authors = ["inga-lovinde <52715130+inga-lovinde@users.noreply.github.com>"]
edition = "2018"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]
nom = "^4.2.3"
nom-peg = "0.1.1"

@ -0,0 +1,29 @@
use std::io::{self, BufRead};
#[macro_use]
extern crate nom;
extern crate nom_peg;
use nom_peg::grammar;
fn main() {
let arithmetic = grammar! {
parse: i64 = <term> "="
term: i64 = <l: value> (" ")* "+" (" ")* <r: term> => { r + l }
| <l: value> (" ")* "*" (" ")* <r: term> => { r * l }
| value
value: i64 = ("0"|"1"|"2"|"3"|"4"|"5"|"6"|"7"|"8"|"9")+ => { result.join("").chars().rev().collect::<String>().parse::<i64>().unwrap() }
| ")" <term> "("
};
let mut result = 0;
let stdin = io::stdin();
for line in stdin.lock().lines() {
let value = arithmetic.parse(&(line.unwrap().chars().rev().collect::<String>() + "=")).unwrap().1;
println!("{}", value);
result += value;
}
println!("{}", result)
}
Loading…
Cancel
Save