Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
102
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.96 KB | None | 0 0
  1. #![allow(dead_code)]
  2.  
  3. struct Parser<'a> {
  4. chars: std::str::Chars<'a>,
  5. }
  6.  
  7. impl<'a> Parser<'a> {
  8. fn new(chars: std::str::Chars<'a>) -> Self {
  9. Parser { chars }
  10. }
  11. }
  12.  
  13. impl<'a> Iterator for Parser<'a> {
  14. type Item = bool;
  15.  
  16. fn next(&mut self) -> Option<Self::Item> {
  17. self.chars.next().and_then(|ch| match ch {
  18. 't' => Some(true),
  19. 'f' => Some(false),
  20. '!' => self.last().map(|r| !r),
  21. '&' => Some(self.fold(true, |r, v| r && v)),
  22. '|' => Some(self.fold(false, |r, v| r || v)),
  23. ',' | '(' => self.next(),
  24. ')' => None,
  25. _ => panic!("Unexpected char {}", ch),
  26. })
  27. }
  28. }
  29.  
  30. struct Solution;
  31.  
  32. impl Solution {
  33. pub fn parse_bool_expr(expression: String) -> bool {
  34. Parser::new(expression.chars()).next().unwrap()
  35. }
  36. }
  37.  
  38. #[cfg(test)]
  39. mod tests {
  40. use super::*;
  41.  
  42. #[test]
  43. fn test_simple() {
  44. assert_eq!(Solution::parse_bool_expr("f".into()), false);
  45. assert_eq!(Solution::parse_bool_expr("t".into()), true);
  46. }
  47.  
  48. #[test]
  49. fn test_not() {
  50. assert_eq!(Solution::parse_bool_expr("!(f)".into()), true);
  51. assert_eq!(Solution::parse_bool_expr("!(t)".into()), false);
  52. }
  53.  
  54. #[test]
  55. fn test_and() {
  56. assert_eq!(Solution::parse_bool_expr("&(f,t)".into()), false);
  57. assert_eq!(Solution::parse_bool_expr("&(t,t)".into()), true);
  58. }
  59.  
  60. #[test]
  61. fn test_or() {
  62. assert_eq!(Solution::parse_bool_expr("|(f,t)".into()), true);
  63. assert_eq!(Solution::parse_bool_expr("|(t,t)".into()), true);
  64. assert_eq!(Solution::parse_bool_expr("|(f,f)".into()), false);
  65. }
  66.  
  67. #[test]
  68. fn test_subexpressions() {
  69. assert_eq!(Solution::parse_bool_expr("|(f,!(f))".into()), true);
  70. assert_eq!(Solution::parse_bool_expr("&(!(f),f)".into()), false);
  71. assert_eq!(
  72. Solution::parse_bool_expr("!(&(&(!(&(f)),&(t),|(f,f,t)),&(t),&(t,t,f)))".into()),
  73. true
  74. );
  75. }
  76. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement