Skip to content

Commit

Permalink
Add problem 2011: Final Value of Variable After Performing Operations
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Dec 19, 2023
1 parent 30ffb16 commit f01099f
Show file tree
Hide file tree
Showing 3 changed files with 57 additions and 0 deletions.
1 change: 1 addition & 0 deletions src/lib.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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;
Original file line number Diff line number Diff line change
@@ -0,0 +1,31 @@
pub struct Solution;

// ------------------------------------------------------ snip ------------------------------------------------------ //

impl Solution {
pub fn final_value_after_operations(operations: Vec<String>) -> 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<String>) -> i32 {
Self::final_value_after_operations(operations)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
pub mod iterative;

pub trait Solution {
fn final_value_after_operations(operations: Vec<String>) -> i32;
}

#[cfg(test)]
mod tests {
use super::Solution;

pub fn run<S: Solution>() {
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,
);
}
}
}

0 comments on commit f01099f

Please sign in to comment.