commit d9064f77dfed36ea304dbfb385167b89b333e752 Author: William Perron Date: Mon Feb 20 12:19:43 2023 -0500 initial commit diff --git a/.gitignore b/.gitignore new file mode 100644 index 0000000..2f7896d --- /dev/null +++ b/.gitignore @@ -0,0 +1 @@ +target/ diff --git a/Cargo.lock b/Cargo.lock new file mode 100644 index 0000000..023d81a --- /dev/null +++ b/Cargo.lock @@ -0,0 +1,7 @@ +# This file is automatically @generated by Cargo. +# It is not intended for manual editing. +version = 3 + +[[package]] +name = "balance" +version = "0.1.0" diff --git a/Cargo.toml b/Cargo.toml new file mode 100644 index 0000000..bd112fd --- /dev/null +++ b/Cargo.toml @@ -0,0 +1,4 @@ +[workspace] +members = [ + "balance" +] diff --git a/balance/.gitignore b/balance/.gitignore new file mode 100644 index 0000000..ea8c4bf --- /dev/null +++ b/balance/.gitignore @@ -0,0 +1 @@ +/target diff --git a/balance/Cargo.toml b/balance/Cargo.toml new file mode 100644 index 0000000..891f8ae --- /dev/null +++ b/balance/Cargo.toml @@ -0,0 +1,8 @@ +[package] +name = "balance" +version = "0.1.0" +edition = "2021" + +# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html + +[dependencies] diff --git a/balance/src/main.rs b/balance/src/main.rs new file mode 100644 index 0000000..0b1c6b7 --- /dev/null +++ b/balance/src/main.rs @@ -0,0 +1,48 @@ +/// Given a string of parenthesis, return the number of parenthesis you need to add to the string in order for it to be balanced. +/// +/// Examples: +/// +/// ```bash +/// > numBalanced(`()`) +/// > 0 +/// +/// > numBalanced(`(()`) +/// > 1 +/// +/// > numBalanced(`))()))))()`) +/// > 6 +/// +/// > numBalanced(`)))))`) +/// > 5 +/// ``` + +fn main() { + println!("{}", balance("))()))))()".to_string())); +} + +fn balance(s: String) -> isize { + let mut to_balance: isize = 0; + + for c in s.chars() { + match c { + '(' => to_balance += 1, + ')' => to_balance -= 1, + _ => unreachable!("unexpected character"), + } + } + + to_balance.abs() +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_balance() { + assert_eq!(0, balance("()".to_string())); + assert_eq!(1, balance("(()".to_string())); + assert_eq!(6, balance("))()))))()".to_string())); + assert_eq!(5, balance(")))))".to_string())); + } +}