Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![allow(dead_code)]
- struct Parser<'a> {
- chars: std::str::Chars<'a>,
- }
- impl<'a> Parser<'a> {
- fn new(chars: std::str::Chars<'a>) -> Self {
- Parser { chars }
- }
- }
- impl<'a> Iterator for Parser<'a> {
- type Item = bool;
- fn next(&mut self) -> Option<Self::Item> {
- self.chars.next().and_then(|ch| match ch {
- 't' => Some(true),
- 'f' => Some(false),
- '!' => self.last().map(|r| !r),
- '&' => Some(self.fold(true, |r, v| r && v)),
- '|' => Some(self.fold(false, |r, v| r || v)),
- ',' | '(' => self.next(),
- ')' => None,
- _ => panic!("Unexpected char {}", ch),
- })
- }
- }
- struct Solution;
- impl Solution {
- pub fn parse_bool_expr(expression: String) -> bool {
- Parser::new(expression.chars()).next().unwrap()
- }
- }
- #[cfg(test)]
- mod tests {
- use super::*;
- #[test]
- fn test_simple() {
- assert_eq!(Solution::parse_bool_expr("f".into()), false);
- assert_eq!(Solution::parse_bool_expr("t".into()), true);
- }
- #[test]
- fn test_not() {
- assert_eq!(Solution::parse_bool_expr("!(f)".into()), true);
- assert_eq!(Solution::parse_bool_expr("!(t)".into()), false);
- }
- #[test]
- fn test_and() {
- assert_eq!(Solution::parse_bool_expr("&(f,t)".into()), false);
- assert_eq!(Solution::parse_bool_expr("&(t,t)".into()), true);
- }
- #[test]
- fn test_or() {
- assert_eq!(Solution::parse_bool_expr("|(f,t)".into()), true);
- assert_eq!(Solution::parse_bool_expr("|(t,t)".into()), true);
- assert_eq!(Solution::parse_bool_expr("|(f,f)".into()), false);
- }
- #[test]
- fn test_subexpressions() {
- assert_eq!(Solution::parse_bool_expr("|(f,!(f))".into()), true);
- assert_eq!(Solution::parse_bool_expr("&(!(f),f)".into()), false);
- assert_eq!(
- Solution::parse_bool_expr("!(&(&(!(&(f)),&(t),|(f,f,t)),&(t),&(t,t,f)))".into()),
- true
- );
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement