2015-02-10 84 views

回答

3

我將:

步驟1:合併兩個表到雙{{2,},{3,B},{1 ,c}}

第2步:對配對進行排序。

第3步:取消合併結果數組。

table1 = {2,3,1} 
table2 = {"a","b","c"} 


-- Comparison function 
function compare(x, y) 
    return x[1] < y[1] 
end 

-- Step 1: Merge in pairs 
for i,v in ipairs(table1) do 
    table1[i] = {table1[i], table2[i]} 
end 

-- Step 2: Sort 
table.sort(table1, compare) 

-- Step 3: Unmerge pairs 
for i, v in ipairs(table1) do 
    table1[i] = v[1] 
    table2[i] = v[2] 
end 

for i = 1,#table1 do 
    print(table1[i], table2[i]) 
end 
0

試試這個代碼,其中使用標準的功能table.sort

table1 = {2,3,1} 
table2 = {"a","b","c"} 

table3 = {} 
for i,v in ipairs(table1) do 
    table3[table2[i]]=v 
end 

table.sort(table1, function (a,b) 
    return table2[a] <= table2[b] 
    end) 

table.sort(table2, function (a,b) 
    return table3[a] <= table3[b] 
    end) 

print("table1") 
for i,v in ipairs(table1) do 
    print(i,v) 
end 

print("table2") 
for i,v in ipairs(table2) do 
    print(i,v) 
end 
+0

有趣的方法但成本太高。 – Tarik 2015-02-11 07:30:08

5

該函數不修改任何一個表中,並返回根據第一排序的第二個表。您可以在第一個表中傳遞鍵的比較,如table.sort

local sort_relative = function(ref, t, cmp) 
    local n = #ref 
    assert(#t == n) 
    local r = {} 
    for i=1,n do r[i] = i end 
    if not cmp then cmp = function(a, b) return a < b end end 
    table.sort(r, function(a, b) return cmp(ref[a], ref[b]) end) 
    for i=1,n do r[i] = t[r[i]] end 
    return r 
end 

例如:

local table1 = {2, 3, 1} 
local table2 = {"a","b","c"} 
local sorted = sort_relative(table1, table2) 
print(table.unpack(sorted)) 

結果:

c a b 
+0

這確實是一種優雅和乾淨的方法。正如諺語所說的那樣,「有一種方法可以讓貓變皮」。 – Tarik 2015-02-11 10:32:47

1

我用鍵值對,並定期排序功能做的工作:

table1 = {2,3,1} 
table2 = {"a","b","c"} 

table3 = {}  
for i, v in ipairs(table2) do 
    table3[table1[i]] = v 
end 

table.sort(table1) 

table2 = {} 
for i = 1,#table1 do 
    table2[i]=table3[table1[i]] 
end 
table3=nil 

for i = 1,#table1 do 
    print(table1[i], table2[i]) 
end 
相關問題