Add exercise 372, 378
This commit is contained in:
parent
84e4493060
commit
c5aa3d4abf
4 changed files with 254 additions and 0 deletions
9
e_372/Cargo.toml
Normal file
9
e_372/Cargo.toml
Normal file
|
@ -0,0 +1,9 @@
|
|||
[package]
|
||||
name = "e_372"
|
||||
version = "0.1.0"
|
||||
authors = ["Emelie Graven <emelie@graven.dev>"]
|
||||
edition = "2021"
|
||||
|
||||
# See more keys and their definitions at https://doc.rust-lang.org/cargo/reference/manifest.html
|
||||
|
||||
[dependencies]
|
48
e_372/src/main.rs
Normal file
48
e_372/src/main.rs
Normal file
|
@ -0,0 +1,48 @@
|
|||
/*!
|
||||
# Description
|
||||
Given a string containing only the characters `x` and `y`, find whether there are the same number of `x`s and `y`s.
|
||||
|
||||
balanced("xxxyyy") => true
|
||||
balanced("yyyxxx") => true
|
||||
balanced("xxxyyyy") => false
|
||||
balanced("yyxyxxyxxyyyyxxxyxyx") => true
|
||||
balanced("xyxxxxyyyxyxxyxxyy") => false
|
||||
balanced("") => true
|
||||
balanced("x") => false
|
||||
|
||||
## Optional bonus
|
||||
|
||||
Given a string containing only lowercase letters, find whether every letter that appears in the string appears the same number of times. Don't forget to handle the empty string (`""`) correctly!
|
||||
|
||||
balanced_bonus("xxxyyyzzz") => true
|
||||
balanced_bonus("abccbaabccba") => true
|
||||
balanced_bonus("xxxyyyzzzz") => false
|
||||
balanced_bonus("abcdefghijklmnopqrstuvwxyz") => true
|
||||
balanced_bonus("pqq") => false
|
||||
balanced_bonus("fdedfdeffeddefeeeefddf") => false
|
||||
balanced_bonus("www") => true
|
||||
balanced_bonus("x") => true
|
||||
balanced_bonus("") => true
|
||||
|
||||
Note that `balanced_bonus` behaves differently than `balanced` for a few inputs, e.g. `"x"`.
|
||||
*/
|
||||
|
||||
use std::collections::HashMap;
|
||||
|
||||
fn main() {
|
||||
println!("{}", balanced(String::from("jbsssssh")));
|
||||
}
|
||||
|
||||
fn balanced(input: String) -> bool {
|
||||
let count: HashMap<char, i32> = input.chars().fold(HashMap::new(), |mut map, ch| {
|
||||
map.entry(ch).and_modify(|n| *n += 1).or_insert(1);
|
||||
map
|
||||
});
|
||||
println!("{:?}", count);
|
||||
let mut values = count.values();
|
||||
if let Some(first) = values.next() {
|
||||
values.all(|x| x == first)
|
||||
} else {
|
||||
true
|
||||
}
|
||||
}
|
Loading…
Add table
Add a link
Reference in a new issue