This commit is contained in:
2024-01-25 21:51:23 +00:00
parent 57d216cdab
commit 7b6a16b662
13 changed files with 493 additions and 0 deletions

View File

@@ -0,0 +1,49 @@
fn main() {
println!("Hello, world!");
}
fn caesar(plain: &str, rshift: u8) -> String {
let alphabet = "abcdefghijklmnopqrstuvwxyz";
let mut out = String::new();
for c in plain.chars() {
if !c.is_alphabetic() {
out.push(c);
continue;
}
let num = (alphabet
.bytes()
.position(|a| a == c.to_lowercase().next().unwrap() as u8)
.unwrap() as u8
+ rshift)
% 26;
let a = alphabet.chars().nth(num as usize).unwrap();
let a = if c.is_uppercase() {
a.to_uppercase().next().unwrap()
} else {
a
};
out.push(a);
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn rot13() {
let message = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz";
let shift = 13;
let out = "NOPQRSTUVWXYZABCDEFGHIJKLMnopqrstuvwxyzabcdefghijklm";
assert_eq!(caesar(message, shift), out);
}
#[test]
fn wiki_caesar() {
let message = "THE QUICK BROWN FOX JUMPS OVER THE LAZY DOG";
let shift = 23;
let out = "QEB NRFZH YOLTK CLU GRJMP LSBO QEB IXWV ALD";
assert_eq!(caesar(message, shift), out);
}
}