luaredefinition

I want to collect the table elements and create a new table. (lua)


I can't find a similar case. Please Help! (lua)

input :

table1={'a','b','c','d','e'}
table2={'aa','bb','cc','dd','ee'}
table3={'aaa','bbb','ccc','ddc','eee'}
...

output :

group1={'a','aa','aaa',...}
group2={'b','bb','bbb',...}
group3={'c','cc','ccc',...}
group4={'d','dd','ddd',...}
group5={'e','ee','eee',...}

Solution

  • Assuming your problem is to group strings made up of different amounts of the same character, I managed to come up with a function I called agroupTables().

    The function:

    function agroupTables(tableOfTables)
      local existentChars = {}
      local agroupedItems = {} 
      for i, currentTable in ipairs(tableOfTables) do
        for j, item in ipairs(currentTable) do
          local character = string.sub(item, 1, 1) -- get the first character of the current item
    
          if not table.concat(existentChars):find(character) or i == 1 then -- checks if character is already in existentChars
            table.insert(existentChars, 1, character) 
            table.insert(agroupedItems, 1, {item})     
          else       
            for v, existentChar in ipairs(existentChars) do
              if item :find(existentChar) then -- check in which group the item should be inserted
                table.insert(agroupedItems[v], 1, item)
                table.sort(agroupedItems[v]) -- sort by the number of characters in the item
              end
            end
          end
        end
      end
      return agroupedItems 
    end
    

    Usage example

    table1 = {'aa','b','c','d','e'}
    table2 = {'a','bb','cc','dd','ee'}
    table3 = {'aaa','bbb','ccc','ddd','eee', 'z'}
    
    agroupedTables = agroupTables({table1, table2, table3})
    
    for i, v in ipairs(agroupedTables) do
      print("group: ".. i .." {")
      for k, j in ipairs(v) do
        print("  " .. j)
      end
      print("}")
    end 
    

    output:

    group: 1 {
       z
    }
    group: 2 {
       e
       ee
       eee
    }
    group: 3 {
       d
       dd
       ddd
    }
    group: 4 {
       c
       cc
       ccc
    }
    group: 5 {
       b
       bb
       bbb
    }
    group: 6 {
       a
       aa
       aaa
    }