Seeking a lua intersection of two arrays, union and complement, and finally get some unfair elements of two arrays.

. 1  - implementation is 
2  - 1. find the intersection of the two arrays 
. 3  - 2. The two arrays are then required with the respective complement of intersection 
. 4  - 3. The two arrays and set up, to give two element array gains injustice 
. 5  - cloning 
. 6  function clone (Object)
 . 7      local lookup_table = {}
 . 8      local  function  _copy (Object)
 . 9          IF  type (Object) ~ = " Table "  the then 
10              return Object
 . 11          ELSEIF lookup_table [Object ] the then 
12              return lookup_table[object]
13         end
14         local new_table = { }
15         lookup_table[object] = new_table
16         for key, value in pairs(object) do
17             new_table[_copy(key)] = _copy(value)
18         end
19         return setmetatable(new_table, getmetatable(object))
20     end
21     return _copy(object)
22 end
23 
24 -- 合并
25 function Merge(...)
26     local arrays = { ... }
27     local result = {}
28     for _,array in ipairs(arrays) do
29         for _, v in ipairs(array) do
30             table.insert(result, v)
31         end
32     end
33 
34     return result
35 end
36 
37 -- 交集
38 function Intersection(t1, t2)
39     local ret = {}
40     for k, v1 in pairs(t1) do
41         local equal = false
42         for k, v2 in pairs(t2) do
43             if v1 == v2 then
44                 equal = true
45                 break
46             end
47         end
48         if equal then
49             table.insert(ret, v1)
50         end
51     end
52     return ret
53 end
54 
55  - the complement of 
56 is  function Complement (T1, T2)
 57 is      - There is a hole, and if this line does not write the reference numeral 1, 2 and the lower reference numeral 3 removed will pass over the array of contamination. 
58      local T1, T2 = Clone (T1), Clone (T2) - numeral. 1 
59      for I = # T1, . 1 , - . 1  do 
60          for J = # T2, . 1 , - . 1  do 
61 is              IF T1 [I] = T2 = [J] the then 
62 is                  table.remove (T1, I)      - numeral 2 
63 is                  table.remove (T2, J)      - numeral. 3 
64              End 
65         End 
66      End 
67  
68      IF # ~ T1 = 0  the then 
69          return T1
 70      the else 
71 is          return T2
 72      End 
73 is  End 
74  
75  - and set 
76  function Aggregate (T1, T2)
 77      local T = Intersection (T1, T2)
 78      - - above said hole because the array t is common, when executed once, the second execution t has no element 
79      local RET = the Merge (Complement (t, T1), Complement (t, T2))
 80      return RET
 81  End 
82  
83 local t1 = {1, 2, 3, 4, 5, 8}
84 
85 local t2 = {1, 3, 5, 6}
86 local agg = Aggregate(t1, t2)
87 
88 for k,v in pairs(agg) do
89     print(k,v)
90 end

 

Guess you like

Origin www.cnblogs.com/erdiba/p/11812699.html