parent
a39203c699
commit
e77d2bca5c
@ -1,7 +1,9 @@
|
|||||||
[workspace]
|
[workspace]
|
||||||
members = [
|
members = [
|
||||||
"balance",
|
"balance",
|
||||||
|
"dice-stats",
|
||||||
"fraction-math",
|
"fraction-math",
|
||||||
|
"parens",
|
||||||
"repeated-groups",
|
"repeated-groups",
|
||||||
"scramble"
|
"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…
Reference in new issue