mirror of
https://bitbucket.org/Mattrixwv/rustclasses.git
synced 2025-12-07 02:43:59 -05:00
Added function to get all permutations of a string
This commit is contained in:
@@ -376,3 +376,53 @@ pub fn getDivisorsBig(goalNumber: num::BigInt) -> Vec<num::BigInt>{
|
||||
divisors.sort();
|
||||
return divisors;
|
||||
}
|
||||
|
||||
//This is a function that creates all permutations of a string and returns a vector of those permutations.
|
||||
pub fn getPermutations(master: String) -> Vec::<String>{
|
||||
return getPermutationsFull(master, 0);
|
||||
}
|
||||
fn getPermutationsFull(masterOrg: String, num: i32) -> Vec::<String>{
|
||||
let mut master = masterOrg;
|
||||
let mut perms = Vec::<String>::new();
|
||||
//Check if the number is out of bounds
|
||||
if((num >= master.len() as i32) || (num < 0)){
|
||||
//Do nothing and return an empty array
|
||||
}
|
||||
//If this is the last possible recurse just return the current string
|
||||
else if(num == (master.len() - 1) as i32){
|
||||
perms.push(master);
|
||||
}
|
||||
//If there are more possible recurses, recurse with the current permutation
|
||||
else{
|
||||
let mut temp = getPermutationsFull(master.clone(), num + 1);
|
||||
perms.extend(temp);
|
||||
//You need to swap the current letter with every possible letter after it
|
||||
//The ones needed to swap before will happen automatically when the function recurses
|
||||
let mut cnt = 1;
|
||||
while((num + cnt) < master.len() as i32){
|
||||
master = swapString(master.clone(), num, (num + cnt));
|
||||
temp = getPermutationsFull(master.clone(), num + 1);
|
||||
perms.extend(temp);
|
||||
master = swapString(master.clone(), num, (num + cnt));
|
||||
cnt += 1;
|
||||
}
|
||||
|
||||
//The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning
|
||||
perms.sort();
|
||||
}
|
||||
|
||||
//Return the array that was built
|
||||
return perms;
|
||||
}
|
||||
pub fn swapString(strng: String, first: i32, second: i32) -> String{
|
||||
let mut bytes = Vec::<u8>::new();
|
||||
bytes.extend_from_slice(strng.as_bytes());
|
||||
let temp = bytes[first as usize];
|
||||
bytes[first as usize] = bytes[second as usize];
|
||||
bytes[second as usize] = temp;
|
||||
let mut swappedString = "".to_string();
|
||||
for loc in 0..bytes.len(){
|
||||
swappedString = format!("{}{}", swappedString, (bytes[loc] as char));
|
||||
}
|
||||
return swappedString;
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user