[Date Prev][Date Next][Thread Prev][Thread Next]
[Date Index]
[Thread Index]
- Subject: Re: Query: table.sort in 2 or n dim arrays.
- From: Philippe Lhoste <PhiLho@...>
- Date: Thu, 26 Aug 2004 18:52:33 +0200
John A GILBERT wrote:
This is a very basic programming query, but I just can't get it worked-out.
Suppose that there were a 2-d array ( the contents of a simple spreadsheet for example) and one wished to sort a column, say:
could the table.sort instruction be applied to such an array were it to be defined in the form Array [ x ][y ]?
Any help would be very much appreciated.
Thank you
John Gilbert.
(Lua used in scripting an accounting program )
At least a simple question I can answer! -)
An example:
-- Sort a 2D array
local colComp = 3 -- Sort using the third column as criterion
local colComp2 = 2 -- Secondary key
local a =
{
{ 6, 2, 99, 1 },
{ 1, 5, 4, 2 },
{ 4, 47, 74, 3 },
{ 7, 3, 99, 4 },
{ 3, 99, 54, 5 },
{ 8, 47, 101, 6 },
{ 2, 7, 14, 7 },
{ 5, 1, 99, 8 },
}
function SimpleSort(el1, el2)
return el1[colComp] < el2[colComp]
end
function TwoKeySort(el1, el2)
-- On way to do that is to make a composite key
local k1 = el1[colComp] * 1000 + el1[colComp2]
local k2 = el2[colComp] * 1000 + el2[colComp2]
return k1 < k2
end
function DumpArray()
for i, t in a do
for j, st in t do
io.write(st .. ' ')
end
io.write('\n')
end
end
-- Simple sort (one key)
print("One key sort")
table.sort(a, SimpleSort)
DumpArray()
-- Reset
colComp = 4
table.sort(a, SimpleSort)
colComp = 3
-- Two key sort (two keys)
print("Two key sort")
table.sort(a, TwoKeySort)
DumpArray()
I think you will get the idea with the above code. Otherwise, don't
hesitate to ask questions.
HTH.
--
Philippe Lhoste
-- (near) Paris -- France
-- Professional programmer and amateur artist
-- http://Phi.Lho.free.fr
-- -- -- -- -- -- -- -- -- -- -- --