aboutsummaryrefslogtreecommitdiff
path: root/src
diff options
context:
space:
mode:
authorNerdyPepper <[email protected]>2019-03-22 11:27:43 +0000
committerNerdyPepper <[email protected]>2019-03-22 11:27:43 +0000
commit62c29360c8e7d0a56599ea4c42f72fadee0eec14 (patch)
tree2d52a1ae5a9c32cf8d96039d4800ce5ed1befc6f /src
parent894cbbca05c860c0eaef2fdc20c63f9012167cc1 (diff)
autobalance brackets
Diffstat (limited to 'src')
-rw-r--r--src/main.rs24
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
33fn 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}