From 62c29360c8e7d0a56599ea4c42f72fadee0eec14 Mon Sep 17 00:00:00 2001 From: NerdyPepper Date: Fri, 22 Mar 2019 16:57:43 +0530 Subject: autobalance brackets --- src/main.rs | 24 ++++++++++++++++++++++++ 1 file changed, 24 insertions(+) diff --git a/src/main.rs b/src/main.rs index 63d0eb2..98db219 100644 --- a/src/main.rs +++ b/src/main.rs @@ -14,6 +14,9 @@ fn main() { let input = input.trim(); let input = input.replace(" ", ""); + let input = autobalance_parens(&input[..]).unwrap(); + + println!("{}", input); if input == "exit" { return @@ -27,4 +30,25 @@ fn main() { } } +fn autobalance_parens(input: &str) -> Result { + let mut balanced = String::from(input); + let mut left_parens = 0; + let mut right_parens = 0; + for letter in input.chars() { + if letter == '(' { + left_parens += 1; + } else if letter == ')' { + right_parens += 1; + } + } + if left_parens > right_parens { + let extras = ")".repeat(left_parens - right_parens); + balanced.push_str(&extras[..]); + Ok(balanced) + } else if left_parens < right_parens { + return Err(format!("Mismatched parentheses")) + } else { + Ok(balanced) + } +} -- cgit v1.2.3