Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- #![feature(vec_remove_item)]
- use std::collections::HashSet;
- pub fn get_perms(mut items: Vec<String>) -> Result<HashSet<String>, String> {
- let mut permutations: HashSet<String> = HashSet::new();
- // Handles instances where either one or less items are passed to the function
- if items.len() < 1 {
- return Err("The Items Vec must have items dawg...".to_string())
- } else if items.len() == 1 {
- permutations.insert(items.pop().unwrap());
- return Ok(permutations)
- }
- for item in &items {
- let mut items_copy = items.clone();
- permutations.insert(item.clone());
- items_copy.remove_item(item);
- complete_perms(&mut permutations, item, &items_copy);
- }
- Ok(permutations)
- }
- fn complete_perms(permutations: &mut HashSet<String>, prepended: &String, items: &[String]) {
- for item in items {
- let new_item = format!("{}{}", prepended, item);
- permutations.insert(new_item);
- }
- if items.len() > 1 {
- for item in items {
- let to_be_prepended = format!("{}{}", prepended, item);
- let mut items_copy = items.to_vec();
- items_copy.remove_item(&item);
- complete_perms(&mut *permutations, &to_be_prepended, &items_copy);
- }
- }
- }
- fn main() {
- let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
- let perms = get_perms(items).unwrap();
- let mut vec_of_items = Vec::new();
- for perm in perms {
- vec_of_items.push(perm);
- }
- vec_of_items.sort();
- for item in vec_of_items {
- println!("{:?}", item);
- }
- }
Add Comment
Please, Sign In to add comment