Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- use std::collections::HashSet;
- enum Patterns {
- Straight,
- EvenSkip,
- OddSkip,
- Modulus
- }
- struct PermutationIterator {
- index: usize,
- root: String,
- rules: Vec<(char, Vec<char>)>,
- buffer: HashSet<String>,
- pattern: Patterns
- }
- mod char_patterns {
- use super::PermutationIterator;
- pub fn straight(_instance: PermutationIterator) -> bool { true }
- pub fn even_skip(instance: PermutationIterator) -> bool { instance.index % 2 == 0 }
- pub fn odd_skip(instance: PermutationIterator) -> bool { instance.index % 1 == 0 }
- pub fn modulus(instance: PermutationIterator) -> bool { instance.index % instance.root.len() == 0 }
- }
- fn index_replace(i: usize, data: &String, replacement: &String) -> String {
- data.chars()
- .take(i-replacement.len())
- .chain(replacement.chars())
- .chain(
- data.chars()
- .skip(i)
- .take(data.len()-i)
- ).collect()
- }
- impl PermutationIterator {
- fn new(word: String, rules: Vec<(char, Vec<char>)>) -> PermutationIterator {
- PermutationIterator {
- index: 0,
- root: word,
- rules: rules,
- buffer: HashSet::new(),
- pattern: Patterns::Straight
- }
- }
- fn with_pattern(mut self, pattern: Patterns) -> Self {
- self.pattern = pattern;
- self
- }
- }
- impl Iterator for PermutationIterator {
- type Item = HashSet<String>;
- fn next(&mut self) -> Option<Self::Item> {
- if self.index <= self.root.len() {
- if self.index == 0 {
- self.buffer.insert(self.root.clone());
- }
- self.index += 1;
- for word in self.buffer.clone() {
- for (rc, replace) in &self.rules {
- for (i, c) in word.chars().enumerate() {
- if rc == &c {
- let check = match &self.pattern {
- Patterns::Straight => char_patterns::straight,
- Patterns::EvenSkip => char_patterns::even_skip,
- Patterns::OddSkip => char_patterns::odd_skip,
- Patterns::Modulus => char_patterns::modulus
- };
- if check(self) {
- for ch in replace {
- self.buffer.insert(index_replace(i+1, &word, &ch.to_string()));
- }
- }
- }
- }
- }
- }
- Some(self.buffer.clone())
- }
- else {
- None
- }
- }
- }
- fn main() {
- let permutator = PermutationIterator::new("password".to_string(), vec![
- ('p', vec!['P', 'p', 'q', 's'])
- ]);
- for x in permutator {
- println!("{:?}", x)
- };
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement