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

[SOLVED] How to group values in double dimension table ?

Started by aquilon, 18 December 2016 - 08:13 PM
aquilon #1
Posted 18 December 2016 - 09:13 PM
Hello,

I try to group values in a double dimension table in an other table, but without duplicates. All attempts i made create a table with duplicates.

Here's an example:

This is my table:

tab1 = {
	   {id = "id1", dmg = 0, qty = 1},
	   {id = "id2", dmg = 0, qty = 1},
	   {id = "id3", dmg = 0, qty = 1},
	   {id = "id1", dmg = 0, qty = 1},
	   }

and i would like an other table like that:

tab2 = {
	   {id = "id1", dmg = 0, qty = 2},
	   {id = "id2", dmg = 0, qty = 1},
	   {id = "id3", dmg = 0, qty = 1},
	   }

So i want my qty values to be summed and tables to be groupe like in the example. Does Someone have an idea for this problem ? Is there a function to do this ?

Thanks for your answers. Sorry if my english is bad, it's not my native language.

EDIT: Here's the real tables:


slot =  {
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 1
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 2
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 3
  {id = 0, dmg = 0, qty = 0},-- slot 4
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 5
  {id = "minecraft:stick", dmg = 0, qty = 1},-- slot 6
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 7
  {id = 0, dmg = 0, qty = 0},-- slot 8
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 9
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 10
  {id = "minecraft:planks", dmg = 5, qty = 1},-- slot 11
  }


item =  {
  {id = "minecraft:planks", dmg = 5, qty = 7},-- item 1
  {id = "minecraft:stick", dmg = 0, qty = 1},-- item 2
  }

slot table is createed with a turtle.getItemDetail() loop on all turtle's slots.

EDIT 2: I use numerical indexes because it correspond to slots number.

EDIT 3: Thx KingofGamesYami for the answer, it helped me, so i made the second table like that:


item = {[ "minecraft:planks" ] = { dmg = 5, qty = 8},}

with this:


for i = 1,#slot do
local id = slot[i].id
  if item[id] == nil then
	item[id] = {["dmg"] = 0, ["qty"] = 0}
	item[id].dmg = slot[i].dmg
	item[id].qty = item[id].qty + slot[i].qty
  else
	item[id].dmg = slot[i].dmg
	item[id].qty = item[id].qty + slot[i].qty
  end
end

This topic is solved, thx !
Edited on 18 December 2016 - 09:38 PM
KingofGamesYami #2
Posted 18 December 2016 - 09:30 PM
While it is possible to do this, may I ask how the original table (tab1) is generated? If you have control over it's creation, you should instead modify your method of adding elements. I would recommend using the id as the key, instead of numerical indexes.

Ex:

local tab1 = {
  id1 = {dmg=0, qty = 1 },
  --//add more entries here
}