From 5e2d87a029be4a4c1c2e826e7548a8e33a782fc2 Mon Sep 17 00:00:00 2001 From: Matthew Ellison Date: Mon, 25 Mar 2019 12:30:32 -0400 Subject: [PATCH] Added a function to return all permutations of a string --- Algorithms.lua | 77 ++++++++++++++++++++++++++++++++++++++++++++++++-- 1 file changed, 75 insertions(+), 2 deletions(-) diff --git a/Algorithms.lua b/Algorithms.lua index 1ab83fc..f35b7ab 100644 --- a/Algorithms.lua +++ b/Algorithms.lua @@ -1,7 +1,7 @@ --luaClasses/Algorithms.lua --Matthew Ellison --- Created: 2-4-19 ---Modified: 2-7-19 +-- Created: 02-04-19 +--Modified: 03-24-19 --This is a file of algorithms that I have found it useful to keep around at all times @@ -191,3 +191,76 @@ function getProd(ary) --Return the product of all elements return prod; end + +function getPermutations(master, num) + --If no num was given make it 0 + local num = num or 1 + local perms = {}; + --Check if the number is out of bounds + if((num > string.len(master)) or (num < 0)) then + --Do nothing and return an empty list + perms = {}; + --If this is the last possible recurse just return the current string + elseif(num == string.len(master)) then + perms[#perms + 1] = master; + --If there are more possible recurses, recurse with the current permutations + else + local temp = getPermutations(master, num + 1); + --Add the elements of temp to perms + for loc = 1, #temp do + perms[#perms + 1] = temp[loc] + end + --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 + for cnt = 1, (string.len(master) - num) do + + --Swap two elements + --Turn it into byte array so you can change values + local tempStr = {}; + for loc = 1, #master do + tempStr[loc] = string.byte(master:sub(loc, loc)); + end + + --Swap the two elements + local tempChar = tempStr[num]; + tempStr[num] = tempStr[num + cnt]; + tempStr[num + cnt] = tempChar; + --Change it back to a string + master = ""; + for loc = 1, #tempStr do + master = master .. string.char(tempStr[loc]); + end + + --Get the permutations after swapping two elements + temp = getPermutations(master, num + 1); + --Add the elements of temp to perms + for loc = 1, #temp do + perms[#perms + 1] = temp[loc] + end + + --Swap the elements back + --Turn it into byte array so you can change values + tempStr = {}; + for loc = 1, #master do + tempStr[loc] = string.byte(master:sub(loc, loc)); + end + --Swap the two elements + tempChar = tempStr[num]; + tempStr[num] = tempStr[num + cnt]; + tempStr[num + cnt] = tempChar; + --Change it back to a string + master = ""; + for loc = 1, #tempStr do + master = master .. string.char(tempStr[loc]); + end + end + end + + --The array is not necessarily in alpha-numeric order. So if this is the full array sort it before returning + if(num == 1) then + table.sort(perms); + end + + --Return the list + return perms; +end