diff options
Diffstat (limited to 'src/main.rs')
-rw-r--r-- | src/main.rs | 24 |
1 files changed, 24 insertions, 0 deletions
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() { | |||
14 | 14 | ||
15 | let input = input.trim(); | 15 | let input = input.trim(); |
16 | let input = input.replace(" ", ""); | 16 | let input = input.replace(" ", ""); |
17 | let input = autobalance_parens(&input[..]).unwrap(); | ||
18 | |||
19 | println!("{}", input); | ||
17 | 20 | ||
18 | if input == "exit" { | 21 | if input == "exit" { |
19 | return | 22 | return |
@@ -27,4 +30,25 @@ fn main() { | |||
27 | } | 30 | } |
28 | } | 31 | } |
29 | 32 | ||
33 | fn autobalance_parens(input: &str) -> Result<String, String> { | ||
34 | let mut balanced = String::from(input); | ||
35 | let mut left_parens = 0; | ||
36 | let mut right_parens = 0; | ||
37 | for letter in input.chars() { | ||
38 | if letter == '(' { | ||
39 | left_parens += 1; | ||
40 | } else if letter == ')' { | ||
41 | right_parens += 1; | ||
42 | } | ||
43 | } | ||
30 | 44 | ||
45 | if left_parens > right_parens { | ||
46 | let extras = ")".repeat(left_parens - right_parens); | ||
47 | balanced.push_str(&extras[..]); | ||
48 | Ok(balanced) | ||
49 | } else if left_parens < right_parens { | ||
50 | return Err(format!("Mismatched parentheses")) | ||
51 | } else { | ||
52 | Ok(balanced) | ||
53 | } | ||
54 | } | ||