tracks/rust/exercises/nucleotide-count/example.rs in trackler-2.0.6.3 vs tracks/rust/exercises/nucleotide-count/example.rs in trackler-2.0.6.4
- old
+ new
@@ -1,13 +1,24 @@
use std::collections::HashMap;
-pub fn count(nucleotide: char, input: &str) -> usize {
- input.chars().filter(|&c| c == nucleotide).count()
+static VALID_NUCLEOTIDES: &'static str = "ACGT";
+
+pub fn count(nucleotide: char, input: &str) -> Result<usize, char> {
+ let valid = |x: char| { VALID_NUCLEOTIDES.contains(x) };
+ if valid(nucleotide) && input.chars().all(valid) {
+ Ok(input.chars().filter(|&c| c == nucleotide).count())
+ } else {
+ Err(nucleotide)
+ }
}
-pub fn nucleotide_counts(input: &str) -> HashMap<char, usize> {
- let mut map: HashMap<char, usize> = "ACGT".chars().map(|c| (c, 0)).collect();
+pub fn nucleotide_counts(input: &str) -> Result<HashMap<char, usize>, char> {
+ let mut map: HashMap<char, usize> = VALID_NUCLEOTIDES.chars().map(|c| (c, 0)).collect();
for nucleotide in input.chars() {
- *map.entry(nucleotide).or_insert(0) += 1;
+ if let Some(n) = map.get_mut(&nucleotide) {
+ *n += 1;
+ } else {
+ return Err(nucleotide);
+ }
}
- map
+ Ok(map)
}