diff --git a/src/lib.rs b/src/lib.rs index 0b4a539b..3cf0f589 100644 --- a/src/lib.rs +++ b/src/lib.rs @@ -1391,6 +1391,7 @@ pub mod problem_1996_the_number_of_weak_characters_in_the_game; pub mod problem_2000_reverse_prefix_of_word; pub mod problem_2006_count_number_of_pairs_with_absolute_difference_k; pub mod problem_2007_find_original_array_from_doubled_array; +pub mod problem_2011_final_value_of_variable_after_performing_operations; #[cfg(test)] mod test_utilities; diff --git a/src/problem_2011_final_value_of_variable_after_performing_operations/iterative.rs b/src/problem_2011_final_value_of_variable_after_performing_operations/iterative.rs new file mode 100644 index 00000000..74810225 --- /dev/null +++ b/src/problem_2011_final_value_of_variable_after_performing_operations/iterative.rs @@ -0,0 +1,31 @@ +pub struct Solution; + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl Solution { + pub fn final_value_after_operations(operations: Vec) -> i32 { + let mut result = 0; + + for operation in operations { + result += if operation.as_bytes()[1] == b'+' { 1 } else { -1 }; + } + + result + } +} + +// ------------------------------------------------------ snip ------------------------------------------------------ // + +impl super::Solution for Solution { + fn final_value_after_operations(operations: Vec) -> i32 { + Self::final_value_after_operations(operations) + } +} + +#[cfg(test)] +mod tests { + #[test] + fn test_solution() { + super::super::tests::run::(); + } +} diff --git a/src/problem_2011_final_value_of_variable_after_performing_operations/mod.rs b/src/problem_2011_final_value_of_variable_after_performing_operations/mod.rs new file mode 100644 index 00000000..f7a335a0 --- /dev/null +++ b/src/problem_2011_final_value_of_variable_after_performing_operations/mod.rs @@ -0,0 +1,25 @@ +pub mod iterative; + +pub trait Solution { + fn final_value_after_operations(operations: Vec) -> i32; +} + +#[cfg(test)] +mod tests { + use super::Solution; + + pub fn run() { + let test_cases = [ + (&["--X", "X++", "X++"] as &[_], 1), + (&["++X", "++X", "X++"], 3), + (&["X++", "++X", "--X", "X--"], 0), + ]; + + for (operations, expected) in test_cases { + assert_eq!( + S::final_value_after_operations(operations.iter().copied().map(str::to_string).collect()), + expected, + ); + } + } +}