PDA

View Full Version : sort 3 numbers


Rikard
08-12-2005, 02:54 AM
Hi im trying to make a function that shall compare 3 numbers and return the smalest first and so on.

i tried to compare 3 numbers in a row but i guess that dont work.

Here is how i have done it:
--Enter global declarations and functions here...
-- sortera tal stigande or in english sort tal(numbers).
function sortera(tal1, tal2, tal3)
if tal1 <= tal2 <= tal3 then
return tal1, tal2, tal3
elseif tal3 <= tal1 <= tal2 then
return tal3, tal1, tal2
elseif tal2 <= tal3 <= tal1 then
return tal2, tal3, tal1
elseif tal2 <= tal1 <= tal3 then
return tal2, tal1, tal3
elseif tal3 <= tal2 <= tal1 then
return tal3, tal2, tal1
elseif tal1 <= tal3 <= tal2 then
return tal1, tal3, tal2
end
end

And on a button i call the funktion

code code code
min, med, max = sortera(solidp1, solidp2, solidp3);
if (min + 0.2) > max then
Dialog.Message("Fel", "Det är för stor skilnad mellan proven. Skilnaden mellan 2 prov får inte vara mer än 0,2. ", MB_OK, MB_ICONINFORMATION, MB_DEFBUTTON1);
else
end
code code code

Corey
08-12-2005, 03:15 AM
Hi. Well there's a couple different approaches to this task. First of all, your approach. I believe if you add a few "and" conditions that your script might work, i.e.:
function sortera(tal1, tal2, tal3)
if tal1 <= tal2 and tal2 <= tal3 then
return tal1, tal2, tal3
elseif tal3 <= tal1 and tal1 <= tal2 then
return tal3, tal1, tal2
elseif tal2 <= tal3 and tal3 <= tal1 then
return tal2, tal3, tal1
elseif tal2 <= tal1 and tal1 <= tal3 then
return tal2, tal1, tal3
elseif tal3 <= tal2 and tal2 <= tal1 then
return tal3, tal2, tal1
elseif tal1 <= tal3 and tal3 <= tal2 then
return tal1, tal3, tal2
end
end

Now for what might be an easier approach, to insert the numbers into an array and then simply sort the array, i.e.:

function sortera(tal1, tal2, tal3)
myTable={tal1,tal2,tal3};
Table.Sort(myTable, nil);
return myTable[1], myTable[2], myTable[3]
end

The second method is probably easier to extend. Hope that helps. :yes

Rikard
08-12-2005, 05:24 AM
Thanks Corey

Corey
08-12-2005, 05:26 AM
No problem. :)