Guest User

Untitled

a guest
May 27th, 2018
84
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.44 KB | None | 0 0
  1. #![feature(vec_remove_item)]
  2.  
  3. use std::collections::HashSet;
  4.  
  5. pub fn get_perms(mut items: Vec<String>) -> Result<HashSet<String>, String> {
  6.  
  7. let mut permutations: HashSet<String> = HashSet::new();
  8.  
  9. // Handles instances where either one or less items are passed to the function
  10. if items.len() < 1 {
  11. return Err("The Items Vec must have items dawg...".to_string())
  12. } else if items.len() == 1 {
  13. permutations.insert(items.pop().unwrap());
  14. return Ok(permutations)
  15. }
  16.  
  17. for item in &items {
  18. let mut items_copy = items.clone();
  19. permutations.insert(item.clone());
  20. items_copy.remove_item(item);
  21. complete_perms(&mut permutations, item, &items_copy);
  22. }
  23.  
  24. Ok(permutations)
  25. }
  26.  
  27. fn complete_perms(permutations: &mut HashSet<String>, prepended: &String, items: &[String]) {
  28. for item in items {
  29. let new_item = format!("{}{}", prepended, item);
  30. permutations.insert(new_item);
  31. }
  32. if items.len() > 1 {
  33. for item in items {
  34. let to_be_prepended = format!("{}{}", prepended, item);
  35. let mut items_copy = items.to_vec();
  36. items_copy.remove_item(&item);
  37. complete_perms(&mut *permutations, &to_be_prepended, &items_copy);
  38. }
  39. }
  40. }
  41.  
  42. fn main() {
  43. let items = vec!["a".to_string(), "b".to_string(), "c".to_string()];
  44. let perms = get_perms(items).unwrap();
  45.  
  46. let mut vec_of_items = Vec::new();
  47.  
  48. for perm in perms {
  49. vec_of_items.push(perm);
  50. }
  51. vec_of_items.sort();
  52. for item in vec_of_items {
  53. println!("{:?}", item);
  54. }
  55. }
Add Comment
Please, Sign In to add comment