This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Luca_S's profile picture

Get all combinations from a table of strings

Started by Luca_S, 18 March 2015 - 05:55 PM
Luca_S #1
Posted 18 March 2015 - 06:55 PM
I need to combine the content of a table to all possible combinations with variable lenght

e.g.

len = 3
chars = {"a","c","4"}
--the funcitons
print(combination)
would return

ac4
a4c
c4a
ca4
4ac
4ca
and

len = 2
chars = {"a","c","4"}
--the funcitons
print(combination)
would return

ac
a4
ca
c4
4a
4c
You probably got the idea, thanks for your help,

Luca
Edited on 29 October 2015 - 03:23 PM
SquidDev #2
Posted 18 March 2015 - 07:47 PM
To be pedantic: You want permutations not combinations, combinations don't care about order.

The PIL book has an article on it here. It is actually about using coroutines to create generators but the theory holds, you can always convert this to use a table and recursive function instead.
Dragon53535 #3
Posted 18 March 2015 - 10:21 PM
I can code up a quite recursive function for you.

Spoiler

local function combine(tbl,maxLen,currLen,usedIndex,currWord)
  if not (tbl) then --#If we don't have a table
    error("Table expected, received "..type(tbl),2)
  currLen = currLen or 1 --# These are validations and checks of if this is the first call.
  usedIndex = usedIndex or {}
  currWord = currWord or ""
  maxLen = ( maxLen and (maxLen <= #tbl) and maxLen) or #tbl
  local totalWord = "" --#Our end word
  for a,v in ipairs(tbl) do --#Loop through our table
    if not usedIndex[a] then --#If we haven't used that letter yet.
      if not (currLen == maxLen) then --#If this isn't the last item
        usedIndex[a] = true --#Say we're using this letter
        totalWord = totalWord..combine(tbl,maxLen,currLen+1,usedIndex,currWord..v) --#Call the function again, and tack it onto the end of the totalWord
        usedIndex[a] = false --#Let go of the letter we're using
      else --#If this IS the last item
        totalWord = totalWord.."\n"..currWord..v --#Tack on the full word to the end.
      end
    end
  end
  return totalWord --#return the full combinations at the end.
end

The code works by looping through the table of characters and then keeping track of what characters have already been gone through. It does however return a multi line string.

Usage:

local tab = {"a", "b" , "c" , "d"}
local combinations = combine(tab,3)
print(combinations)





This is untested code, I will make sure it works, just not on my desktop atm Tested and working.
Edited on 18 March 2015 - 09:35 PM