ctci/src/chapter_1/problem_1.rs

53 lines
1.3 KiB
Rust
Raw Normal View History

2026-02-28 18:10:12 -08:00
use tracing::debug;
use super::error::{Chapter1Error::Problem1Error, Chapter1Result};
/// Check Permutation: Given two strings, write a method to decide if one is a permutation of the other
pub fn is_permutation(string: &str, string2: &str) -> Chapter1Result<()> {
let string = String::from(string);
let mut string2 = String::from(string2);
for char1 in string.chars() {
debug!("char 1: {char1}");
eliminate(char1, &mut string2)?
}
Ok(())
}
fn eliminate(char1: char, string2: &mut String) -> Chapter1Result<()> {
for (idx, char2) in string2.chars().enumerate() {
debug!("char 2: {char2}");
if char1 == char2 {
debug!("match remove");
string2.remove(idx);
return Ok(());
}
}
Err(Problem1Error)
}
#[cfg(test)]
mod test_problem_1 {
use super::*;
use tracing_test::traced_test;
#[traced_test]
#[test]
fn test_guh() {
assert!(is_permutation("guh", "hug").is_ok());
}
#[test]
fn test_whale() {
assert!(is_permutation("whale", "lewah").is_ok());
}
#[test]
fn test_zeb() {
assert!(is_permutation("zeb", "bera").is_err());
}
#[test]
fn test_bez() {
assert!(is_permutation("szeb", "bez").is_err());
}
}