From f6b72beab9f09a9bf41e9fb75956754ab4bee573 Mon Sep 17 00:00:00 2001 From: jackfiled Date: Sun, 10 Mar 2024 10:41:58 +0800 Subject: [PATCH] 20240310 Finished --- src/problem/mod.rs | 3 +- src/problem/p299_bulls_and_cows.rs | 55 ++++++++++++++++++++++++++++++ 2 files changed, 57 insertions(+), 1 deletion(-) create mode 100644 src/problem/p299_bulls_and_cows.rs diff --git a/src/problem/mod.rs b/src/problem/mod.rs index 23ce6f1..4d7205b 100644 --- a/src/problem/mod.rs +++ b/src/problem/mod.rs @@ -68,4 +68,5 @@ mod p1976_number_of_ways_to_arrive_at_destination; mod p2917_find_the_k_or_of_an_array; mod p2575_find_the_divisibility_array_of_a_string; mod p2834_find_the_minimum_possible_sum_of_a_beautiful_array; -mod p2386_find_the_k_sum_of_an_array; \ No newline at end of file +mod p2386_find_the_k_sum_of_an_array; +mod p299_bulls_and_cows; \ No newline at end of file diff --git a/src/problem/p299_bulls_and_cows.rs b/src/problem/p299_bulls_and_cows.rs new file mode 100644 index 0000000..4ba8c60 --- /dev/null +++ b/src/problem/p299_bulls_and_cows.rs @@ -0,0 +1,55 @@ +/** + * [299] Bulls and Cows + */ +pub struct Solution {} + + +// submission codes start here +use std::collections::HashMap; + +impl Solution { + pub fn get_hint(secret: String, guess: String) -> String { + let secret: Vec = secret.chars().collect(); + let guess: Vec = guess.chars().collect(); + + let mut bull = 0; + let mut cow_map = HashMap::new(); + let mut cow_candidate = Vec::with_capacity(guess.len()); + + for i in 0..secret.len() { + if secret[i] == guess[i] { + bull += 1; + } else { + let entry = cow_map.entry(secret[i]).or_insert(0); + *entry += 1; + + cow_candidate.push(guess[i]); + } + } + + let mut cow = 0; + for candidate in cow_candidate { + if let Some(entry) = cow_map.get_mut(&candidate) { + if *entry != 0 { + cow += 1; + *entry -= 1; + } + } + } + + format!("{}A{}B", bull, cow) + } +} + +// submission codes end + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_299() { + assert_eq!("1A3B", Solution::get_hint("1807".to_owned(), "7810".to_owned())); + assert_eq!("1A1B", Solution::get_hint("1123".to_owned(), "0111".to_owned())); + } +}