ACSUtils Wiki

An ACS library for ZDoom-based ports

User Tools

Site Tools


new:array

This is an old revision of the document!


Array sorting and shuffling

These functions will be added in ACSUtils 1.8.0

SortArray

void SortArray(int begin, int end, str lt, str swap)

Sorts an array with indices in range [begin, end). lt and swap are names of scripts that the function will call.

  • script “lt” (int a, int b) must return the result of array[a] < array[b] using SetReturnValue. If you return array[a] > array[b], sorting order is reversed.
  • script “swap” (int a, int b) must swap array[a] with array[b].

The sorted array may actually be an array of objects with multiple fields. lt can implement multi-field sorting. swap can swap all fields in the two array cells.

Example: sorting a simple array of numbers:

int array[10];

script "compare_two_elements" (int a, int b)
{
    SetResultValue(array[a] < array[b]);
}

script "swap_two_elements" (int a, int b)
{
    int temp = array[a];
    array[a] = array[b];
    array[b] = temp;
}

function void SortTheArray(void)
{
    SortArray(0, 10, "compare_two_elements", "swap_two_elements");
    
    // You can also sort sub-arrays:
    SortArray(3, 8, "compare_two_elements", "swap_two_elements");
}

Example: making a scoreboard sorted by score:

int PlayerNumbers[MAX_PLAYERS];
int PlayerScores[MAX_PLAYERS];
int NumPlayers;

script "lt" (int a, int b)
{
    if (PlayerScores[a] == PlayerScores[b])
    {
        // Scores are same, sort by name then
        if (StrCmp(PlayerName(PlayerNumbers[a]), PlayerName(PlayerNumbers[b]) == -1);
            return true;
    }
        
    // Using > instead of < reverses sorting by score
    return PlayerScores[a] > PlayerScores[b];
}

script "swap" (int a, int b)
{
    swap(PlayerNumbers[a], PlayerNumbers[b]);
    Players[a] = r1;
    Players[b] = r2;
    
    swap(PlayerScores[a], PlayerScores[b]);
    PlayerScores[a] = r1;
    PlayerScores[b] = r2;
}

function void BuildScoreboard(void)
{
    // Fill scoreboard without sorting
    for (int player = 0; player < MAX_PLAYERS; player++)
    {
        if (PlayerInGame(player))
            continue;
        PlayerNumbers[NumPlayers] = player;
        PlayerScores[NumPlayers] = GET_PLAYER_SCORE(player);
        NumPlayers++;
    }
    
    // Sort it by score
    SortArray(0, NumPlayers, "lt", "swap");
}
new/array.1519164413.txt.gz · Last modified: 2018/02/21 00:06 by korshun