Created
January 24, 2020 11:34
-
-
Save NeuroWhAI/1c368c8cb668327207aed8e396c59d4c 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
use std::iter::FromIterator; | |
/// A rule for repositioning characters in a string. | |
struct Rule(Vec<usize>); | |
impl Rule { | |
/// Applies this rule to the input and returns the result. | |
/// | |
/// # Examples | |
/// | |
/// Basic usage: | |
/// | |
/// ``` | |
/// let r = Rule::from(&[3, 2, 1, 4][..]); | |
/// assert_eq!("CBAD", r.apply("ABCD").unwrap()); | |
/// ``` | |
fn apply<T>(&self, input: T) -> Result<String, ()> | |
where | |
T: Into<String>, | |
{ | |
let input: Vec<_> = input.into().chars().collect(); | |
if self.0.len() == input.len() { | |
let mut output = String::new(); | |
for &i in &self.0 { | |
output.push(input[i - 1]); | |
} | |
Ok(output) | |
} else { | |
Err(()) | |
} | |
} | |
/// Disapplies this rule to the input and returns the result. | |
/// | |
/// # Examples | |
/// | |
/// Basic usage: | |
/// | |
/// ``` | |
/// let r = Rule::from(&[3, 2, 1, 4][..]); | |
/// let input = "ABCD"; | |
/// let output = r.apply(input).unwrap(); | |
/// assert_eq!(input, &r.restore(output).unwrap()); | |
/// ``` | |
fn restore<T>(&self, input: T) -> Result<String, ()> | |
where | |
T: Into<String>, | |
{ | |
let input: Vec<_> = input.into().chars().collect(); | |
if self.0.len() == input.len() { | |
let mut output = Vec::new(); | |
output.resize(input.len(), '\0'); | |
for (&i, ch) in self.0.iter().zip(input) { | |
output[i - 1] = ch; | |
} | |
Ok(String::from_iter(output)) | |
} else { | |
Err(()) | |
} | |
} | |
} | |
impl From<&[usize]> for Rule { | |
fn from(slice: &[usize]) -> Rule { | |
Rule(Vec::from(slice)) | |
} | |
} | |
fn main() { | |
let rule1 = Rule::from(&[3, 2, 1, 4][..]); | |
let input = "ABCD"; | |
let output = rule1.apply(input).unwrap(); | |
let restore = rule1.restore(&output).unwrap(); | |
assert_eq!(&output, "CBAD"); | |
assert_eq!(&restore, input); | |
println!("{} -> {}", input, output); | |
println!("{} -> {}", output, restore); | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment