Skip to content

Commit

Permalink
Add problem 2325: Decode the Message
Browse files Browse the repository at this point in the history
  • Loading branch information
EFanZh committed Nov 16, 2024
1 parent 454de0a commit 5fba149
Show file tree
Hide file tree
Showing 3 changed files with 75 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 @@ -1724,6 +1724,7 @@ pub mod problem_2317_maximum_xor_after_operations;
pub mod problem_2319_check_if_matrix_is_x_matrix;
pub mod problem_2320_count_number_of_ways_to_place_houses;
pub mod problem_2321_maximum_score_of_spliced_array;
pub mod problem_2325_decode_the_message;

#[cfg(test)]
mod test_utilities;
47 changes: 47 additions & 0 deletions src/problem_2325_decode_the_message/iterative.rs
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
pub struct Solution;

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

impl Solution {
pub fn decode_message(key: String, message: String) -> String {
let mut mapping = [0_u8; 26];
let mut next = b'a';

for from in key.into_bytes() {
if let Some(slot @ 0) = mapping.get_mut(usize::from(from).wrapping_sub(usize::from(b'a'))) {
*slot = next;
next += 1;

if next > b'z' {
break;
}
}
}

let mut result = message.into_bytes();

for from in &mut result {
if let Some(&to) = mapping.get(usize::from(*from).wrapping_sub(usize::from(b'a'))) {
*from = to;
}
}

String::from_utf8(result).unwrap()
}
}

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

impl super::Solution for Solution {
fn decode_message(key: String, message: String) -> String {
Self::decode_message(key, message)
}
}

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

pub trait Solution {
fn decode_message(key: String, message: String) -> String;
}

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

pub fn run<S: Solution>() {
let test_cases = [
(
("the quick brown fox jumps over the lazy dog", "vkbs bs t suepuv"),
"this is a secret",
),
(
("eljuxhpwnyrdgtqkviszcfmabo", "zwx hnfx lqantp mnoeius ycgk vcnjrdb"),
"the five boxing wizards jump quickly",
),
];

for ((key, message), expected) in test_cases {
assert_eq!(S::decode_message(key.to_string(), message.to_string()), expected);
}
}
}

0 comments on commit 5fba149

Please sign in to comment.