Advertisement
Guest User

Untitled

a guest
Jul 23rd, 2019
107
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.30 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. '!' => {
  21. assert_eq!(self.chars.next(), Some('('));
  22. let r = self.next().map(|r| !r);
  23. assert_eq!(self.chars.next(), Some(')'));
  24. r
  25. }
  26. '&' => {
  27. assert_eq!(self.chars.next(), Some('('));
  28. Some(self.fold(true, |r, v| r && v))
  29. }
  30. '|' => {
  31. assert_eq!(self.chars.next(), Some('('));
  32. Some(self.fold(false, |r, v| r || v))
  33. }
  34. ',' => self.next(),
  35. ')' => None,
  36. _ => panic!("Unexpected char {}", ch),
  37. })
  38. }
  39. }
  40.  
  41. struct Solution;
  42.  
  43. impl Solution {
  44. pub fn parse_bool_expr(expression: String) -> bool {
  45. Parser::new(expression.chars()).next().unwrap()
  46. }
  47. }
  48.  
  49. #[cfg(test)]
  50. mod tests {
  51. use super::*;
  52.  
  53. #[test]
  54. fn test_simple() {
  55. assert_eq!(Solution::parse_bool_expr("f".into()), false);
  56. assert_eq!(Solution::parse_bool_expr("t".into()), true);
  57. }
  58.  
  59. #[test]
  60. fn test_not() {
  61. assert_eq!(Solution::parse_bool_expr("!(f)".into()), true);
  62. assert_eq!(Solution::parse_bool_expr("!(t)".into()), false);
  63. }
  64.  
  65. #[test]
  66. fn test_and() {
  67. assert_eq!(Solution::parse_bool_expr("&(f,t)".into()), false);
  68. assert_eq!(Solution::parse_bool_expr("&(t,t)".into()), true);
  69. }
  70.  
  71. #[test]
  72. fn test_or() {
  73. assert_eq!(Solution::parse_bool_expr("|(f,t)".into()), true);
  74. assert_eq!(Solution::parse_bool_expr("|(t,t)".into()), true);
  75. assert_eq!(Solution::parse_bool_expr("|(f,f)".into()), false);
  76. }
  77.  
  78. #[test]
  79. fn test_subexpressions() {
  80. assert_eq!(Solution::parse_bool_expr("|(f,!(f))".into()), true);
  81. assert_eq!(Solution::parse_bool_expr("&(!(f),f)".into()), false);
  82. assert_eq!(
  83. Solution::parse_bool_expr("!(&(&(!(&(f)),&(t),|(f,f,t)),&(t),&(t,t,f)))".into()),
  84. true
  85. );
  86. }
  87. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement