Scroll through LUA tables

3

I have two tables created in LUA. I want to go through if there is an equal value between the two. Something like this.

table1={5,10,30,40,50,60,40}
table2={10,30,40}
for i=1,#table1 do
  if table1[i]==table2[i] then
    print("valor igual")
  end
end

The problem is that as Table 1 is larger than two, you will not be able to traverse the whole table. How can I adapt this?

    
asked by anonymous 05.06.2015 / 01:06

2 answers

2

If you do not have memory or disk space to create an ordered copy of either table, there is no way: you need two for s:

for i=1,#table1 do
  for j=1,#table2 do
    if table1[i]==table2[j] then
      print("valor igual")
    end
  end
end

(note the difference in indexes)

Obviously, the problem is that if you can not afford the cost of sorting the tables, it probably implies that they are giants, and so the above algorithm is O (mn), which is a cost that you too can not pay, unless for some reason processing time is much cheaper than disk and / or memory.

What you can do in this case is a probabilistic approach: you can create a bloom filter

If you really need to squeeze the performance of this comparison, you have a paper by Ricardo Baeza-Yates which deals with ordered list intersection algorithms.

If the two lists are lowercase, the two% s with% s at the beginning of this answer are the best solution - the firsts that the other solutions involve will end up costing more than making all comparisons between all pairs of values

    
05.06.2015 / 01:30
2

If you can create another table, try this:

table1={5,10,30,40,50,60,40}
table2={10,30,40}

values={}
for k,v in pairs(table1) do
    values[v]=true
end
for k,v in pairs(table2) do
    if values[v] then
        print(v)
    end
end

This method spends time and memory O (m + n) .

    
10.06.2015 / 19:00