PDA

View Full Version : Generic Sorting

Novo
05-22-2007, 05:34 AM
For those who wanted to know what use does variable functions do... Here's an example:

class: math-sort

function defaultSort( sideA, sideB )
{
return (sideA < sideB);
}

function sortList( list, compFunc )
{
this.sortFunc = ( compFunc == null ? this.defaultSort : compFunc );

for ( temp.i = 0; temp.i < list.size() - 1; temp.i++ )
{
temp.min = temp.i;
for ( temp.j = temp.i + 1; temp.j < list.size(); temp.j ++ )
{
if ( sortFunc( list[temp.j], list[temp.min]) )
temp.min = temp.j;
}

temp.b = list[temp.i];
list[temp.i] = list[temp.min];
list[temp.min] = temp.b;
}

return list;
}

function onCreated()
{
join("math-sort");
temp.l = {{1,3},{3,2},{2,1},{4,2} };

temp.func = function(sideA, sideB)
{
return ( sideA[0] < sideB[0] );
};

temp.list = sortList( temp.l, temp.func );
echo( temp.list ); // {{1, 3}, {2, 1}, {3, 2}, {4, 2}}
}

You could have them sorted by this function...

A practical use of this is sorting a list of NPCs with respect to how far it is!
One way to do this is simply defining this function:

temp.func = function(sideA, sideB)
{
return ( (sideA.x - this.x)^2 + (sideA.y - this.y)^2 < (sideB.x - this.x)^2 + (sideB.y - this.y)^2 );
};

zokemon
05-22-2007, 01:49 PM
Good job Novo!
I didn't think of using it that way :)

xAndrewx
05-22-2007, 10:53 PM
You suck, at trying to disappoint me that is!

sam_is_me
05-23-2007, 07:32 PM
lol, i really cant read that script...
but if it works, hey, good job.