Created
August 16, 2015 05:09
-
-
Save zummenix/3c8454ab8a1b8400165a to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#[cfg(test)] | |
#[macro_use(expect)] | |
extern crate expectest; | |
#[cfg(not(test))] | |
fn main() { | |
println!("{}", mangle("This challenge doesn't seem so hard.")); | |
} | |
#[derive(Copy, Clone)] | |
enum MaskedChar { | |
Lowercase, | |
Uppercase, | |
Misc(char), | |
} | |
fn mask_char(ch: char) -> MaskedChar { | |
if ch.is_lowercase() { | |
MaskedChar::Lowercase | |
} else if ch.is_uppercase() { | |
MaskedChar::Uppercase | |
} else { | |
MaskedChar::Misc(ch) | |
} | |
} | |
fn to_mask(word: &[char]) -> Vec<MaskedChar> { | |
word.iter().cloned().map(mask_char).collect() | |
} | |
fn char_to_char((c, m): (char, MaskedChar)) -> char { | |
match m { | |
MaskedChar::Misc(ch) => ch, | |
MaskedChar::Uppercase => c.to_uppercase().next().unwrap_or(c), | |
MaskedChar::Lowercase => c.to_lowercase().next().unwrap_or(c), | |
} | |
} | |
fn fill_mask(word: &[char], mask: &[MaskedChar]) -> String { | |
word.iter().cloned().zip(mask.iter().cloned()).map(char_to_char).collect() | |
} | |
fn sorted_chars(word: &str) -> Vec<char> { | |
use std::cmp::Ordering; | |
let mut chars: Vec<char> = word.to_lowercase().chars().collect(); | |
chars.sort_by(|a, b| { | |
if a.is_alphabetic() && b.is_alphabetic() { | |
a.cmp(b) | |
} else { | |
Ordering::Equal | |
} | |
}); | |
chars | |
} | |
fn chars(word: &str) -> Vec<char> { | |
word.chars().collect() | |
} | |
pub fn mangle(s: &str) -> String { | |
s.split_whitespace().map(|word| { | |
fill_mask(&sorted_chars(word), &to_mask(&chars(word))) | |
}).collect::<Vec<_>>().connect(" ") | |
} | |
#[cfg(test)] | |
mod tests { | |
use super::*; | |
use expectest::prelude::*; | |
#[test] | |
fn phrase_1() { | |
let string = "This challenge doesn't seem so hard."; | |
expect!(mangle(string)).to(be_equal_to("Hist aceeghlln denos't eems os adhr.")); | |
} | |
#[test] | |
fn phrase_2() { | |
let string = "There are more things between heaven and earth, Horatio, than are dreamt of in your philosophy."; | |
expect!(mangle(string)).to(be_equal_to("Eehrt aer emor ghinst beeentw aeehnv adn aehrt, Ahioort, ahnt aer ademrt fo in oruy hhilooppsy.")); | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment