Example:
table1 = {2,3,1}
table2 = {a,b,c}
to
table1 = {1,2,3}
table2 = {c,a,b}
Example:
table1 = {2,3,1}
table2 = {a,b,c}
to
table1 = {1,2,3}
table2 = {c,a,b}
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
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
I use key value pairs and the regular sort function to do the job:
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
Try this code, which uses the standard function 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
© 2022 - 2024 — McMap. All rights reserved.