ID:178641
 
if you have a list with random numeric components, how could they be sorted and output in some type of ascending or descending order? One reason I am asking is so I can make a who() function/verb that lists all of the characters in the game by descending order of different status variables.
Gakumerasara wrote:
if you have a list with random numeric components, how could they be sorted and output in some type of ascending or descending order? One reason I am asking is so I can make a who() function/verb that lists all of the characters in the game by descending order of different status variables.

One way to do it is to make a proc that will start with a high number and decrease it by increments, checking each time to see if there's a member of the list with the same number.

mob/verb/who()
for(var/mob/M in Descending()) world << M

proc/Descending()
var/list/moblist = new
for (var/i=500,i>=1,i--) //goes from 500 down to 1
for(var/mob/M in world)
if (M.stat == i) moblist += M

return moblist

There might be a better way to do it, but that was what I thought of.

Z
var/maxpos = 1
var/maxval = 0
var/temp
for(var/count = 1; count <= somelist.len; count++)
maxpos = count
maxval = somelist[count]
for(var/count2 = count; count2 <= somelist.len; count2++)
if(somelist[count2] > maxval)
maxpos = count2
maxval = somelist[count2]
if(maxpos != count)
temp = somelist[count]
somelist[count] = maxval
somelist[maxpos] = temp

Thats the basic setup for a sorting algorithm we had to make in my C++ class. I haven't compiled that but the method should work.

What it does is it starts at the first position and looks at all other values looking for the largest value. Then it swaps the largest value with the first value. Then it starts from the second position and looks for the next greatest value in the list and then swaps it with the second value. This continues until the entire list has been sorted in descending order. To make it work in ascending order you would just switch the:
if(somelist[count2] > maxval)
to:
if(somelist[count2] < minval)

This would be more efficient with pointer arithmatic but I'm not sure if you can do that in byond.