add balance parenthesis (issue #287?)

main
William Perron 2 years ago
parent a39203c699
commit e77d2bca5c

27
Cargo.lock generated

@ -12,6 +12,20 @@ version = "1.0.0"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "baf1de4339761588bc0619e3cbc0120ee582ebb74b53b4efbf79117bd2da40fd"
[[package]]
name = "dice-stats"
version = "0.1.0"
dependencies = [
"itertools",
"rand",
]
[[package]]
name = "either"
version = "1.8.1"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "7fcaabb2fef8c910e7f4c7ce9f67a1283a1715879a7c230ca9d6d1ae31f16d91"
[[package]]
name = "fraction-math"
version = "0.1.0"
@ -27,12 +41,25 @@ dependencies = [
"wasi",
]
[[package]]
name = "itertools"
version = "0.10.5"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "b0fd2260e829bddf4cb6ea802289de2f86d6a7a690192fbe91b3f46e0f2c8473"
dependencies = [
"either",
]
[[package]]
name = "libc"
version = "0.2.139"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "201de327520df007757c1f0adce6e827fe8562fbc28bfd9c15571c66ca1f5f79"
[[package]]
name = "parens"
version = "0.1.0"
[[package]]
name = "ppv-lite86"
version = "0.2.17"

@ -1,7 +1,9 @@
[workspace]
members = [
"balance",
"dice-stats",
"fraction-math",
"parens",
"repeated-groups",
"scramble"
]

@ -0,0 +1,8 @@
[package]
name = "parens"
version = "0.1.0"
edition = "2021"
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
[dependencies]

@ -0,0 +1,52 @@
use std::env::args;
fn main() {
let mut args = args();
// Consume the first arg, it's the executable name, we don't care in this
// context.
let _ = args.next();
match args.next() {
Some(parens) => match to_balance(parens) {
Ok(balance) => println!("{}", balance),
Err(e) => eprintln!("{}", e),
},
None => println!("Nothing to do. Exiting..."),
}
}
fn to_balance(input: String) -> Result<isize, String> {
let mut diff = 0;
for c in input.chars() {
match c {
'(' => diff += 1,
')' => diff -= 1,
c => return Err(format!("unexpected character {}", c)),
}
}
Ok(diff)
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn balance_parens() {
let cases: Vec<(String, Result<isize, String>)> = vec![
("()".to_string(), Ok(0)),
("(()".to_string(), Ok(1)),
("))()))))()".to_string(), Ok(-6)),
(")))))".to_string(), Ok(-5)),
(
"foobar".to_string(),
Err("unexpected character f".to_string()),
),
];
for c in cases {
assert_eq!(c.1, to_balance(c.0));
}
}
}
Loading…
Cancel
Save