Skip to content

Commit

Permalink
Add problem 2125: Number of Laser Beams in a Bank
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Jun 22, 2024
1 parent e58f05f commit 3ebf52e
Show file tree
Hide file tree
Showing 3 changed files with 69 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 @@ -1526,6 +1526,7 @@ pub mod problem_2114_maximum_number_of_words_found_in_sentences;
pub mod problem_2116_check_if_a_parentheses_string_can_be_valid;
pub mod problem_2119_a_number_after_a_double_reversal;
pub mod problem_2124_check_if_all_as_appears_before_all_bs;
pub mod problem_2125_number_of_laser_beams_in_a_bank;
pub mod problem_2129_capitalize_the_title;
pub mod problem_2130_maximum_twin_sum_of_a_linked_list;
pub mod problem_2131_longest_palindrome_by_concatenating_two_letter_words;
Expand Down
44 changes: 44 additions & 0 deletions src/problem_2125_number_of_laser_beams_in_a_bank/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,44 @@
pub struct Solution;

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

impl Solution {
pub fn number_of_beams(bank: Vec<String>) -> i32 {
let mut result = 0;
let mut prev = 0;

for bank in bank {
let offset = (u32::from(b'0') * bank.len() as u32).wrapping_neg();

let devices = bank
.as_bytes()
.iter()
.fold(offset, |sum, &c| sum.wrapping_add(u32::from(c)));

drop(bank);

if devices != 0 {
result += prev * devices;
prev = devices;
}
}

result as _
}
}

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

impl super::Solution for Solution {
fn number_of_beams(bank: Vec<String>) -> i32 {
Self::number_of_beams(bank)
}
}

#[cfg(test)]
mod tests {
#[test]
fn test_solution() {
super::super::tests::run::<super::Solution>();
}
}
24 changes: 24 additions & 0 deletions src/problem_2125_number_of_laser_beams_in_a_bank/mod.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,24 @@
pub mod iterative;

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

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

pub fn run<S: Solution>() {
let test_cases = [
(&["011001", "000000", "010100", "001000"] as &[_], 8),
(&["000", "111", "000"], 0),
];

for (bank, expected) in test_cases {
assert_eq!(
S::number_of_beams(bank.iter().copied().map(str::to_string).collect()),
expected,
);
}
}
}

0 comments on commit 3ebf52e

Please sign in to comment.