Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sort two tables simultaneously by using one of tables order?

Tags:

lua

lua-table

Example:

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

to

table1 = {1,2,3}
table2 = {c,a,b}
like image 819
Frank05 Avatar asked Feb 10 '15 22:02

Frank05


2 Answers

This function does not modify either table, and returns the second table sorted according to the first. You can pass a comparison for keys in the first table, like in 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

For instance:

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

results in:

c   a   b
like image 88
catwell Avatar answered Sep 18 '22 03:09

catwell


I would:

Step 1: Merge the two tables into pairs {{2,a},{3,b},{1,c}}

Step 2: Sort the pairs.

Step 3: Unmerge the resulting array.

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
like image 43
Tarik Avatar answered Sep 19 '22 03:09

Tarik