This shows you the differences between two versions of the page.
| Next revision | Previous revision | ||
| new:array [2018/02/20 21:38] – created korshun | new:array [2018/02/21 11:57] (current) – korshun | ||
|---|---|---|---|
| Line 2: | Line 2: | ||
| <note warning> | <note warning> | ||
| + | |||
| + | Array sorting and shuffling functions use script names as callbacks. | ||
| ===== SortArray ===== | ===== SortArray ===== | ||
| Line 7: | Line 9: | ||
| '' | '' | ||
| - | Sorts an array with indices in range [begin, end). | + | Sorts an array with indices in range [begin, end). '' |
| + | |||
| + | * '' | ||
| + | * '' | ||
| - | '' | + | The sorted array may actually be an array of objects with multiple fields. |
| - | '' | + | <note important> |
| - | Example: sorting a simple array: | + | Example: sorting a simple array of numbers: |
| < | < | ||
| Line 39: | Line 44: | ||
| </ | </ | ||
| - | Example: | + | Example: |
| < | < | ||
| - | int Players[MAX_PLAYERS]; | + | int PlayerNumbers[MAX_PLAYERS]; |
| int PlayerScores[MAX_PLAYERS]; | int PlayerScores[MAX_PLAYERS]; | ||
| int NumPlayers; | int NumPlayers; | ||
| Line 48: | Line 53: | ||
| script " | script " | ||
| { | { | ||
| - | | + | |
| + | { | ||
| + | // Scores are same, sort by name then | ||
| + | if (StrCmp(PlayerName(PlayerNumbers[a]), | ||
| + | return true; | ||
| + | } | ||
| + | |||
| + | // Using > instead of < reverses sorting by score | ||
| + | return PlayerScores[a] > PlayerScores[b]; | ||
| } | } | ||
| script " | script " | ||
| { | { | ||
| - | swap(Players[a], Players[b]); | + | swap(PlayerNumbers[a], PlayerNumbers[b]); |
| Players[a] = r1; | Players[a] = r1; | ||
| Players[b] = r2; | Players[b] = r2; | ||
| Line 64: | Line 77: | ||
| function void BuildScoreboard(void) | function void BuildScoreboard(void) | ||
| { | { | ||
| + | // Clear scoreboard | ||
| + | NumPlayers = 0; | ||
| + | |||
| // Fill scoreboard without sorting | // Fill scoreboard without sorting | ||
| for (int player = 0; player < MAX_PLAYERS; | for (int player = 0; player < MAX_PLAYERS; | ||
| Line 69: | Line 85: | ||
| if (PlayerInGame(player)) | if (PlayerInGame(player)) | ||
| continue; | continue; | ||
| - | | + | |
| PlayerScores[NumPlayers] = GET_PLAYER_SCORE(player); | PlayerScores[NumPlayers] = GET_PLAYER_SCORE(player); | ||
| NumPlayers++; | NumPlayers++; | ||
| Line 78: | Line 94: | ||
| } | } | ||
| </ | </ | ||
| + | |||
| + | ===== ShuffleArray ===== | ||
| + | |||
| + | '' | ||
| + | |||
| + | Randomly reorders elements of an array with indices in range [begin, end). '' | ||
| + | |||
| + | Example: | ||
| + | |||
| + | < | ||
| + | int array[10]; | ||
| + | |||
| + | script " | ||
| + | { | ||
| + | int temp = array[a]; | ||
| + | array[a] = array[b]; | ||
| + | array[b] = temp; | ||
| + | } | ||
| + | |||
| + | function void ShuffleTheArray(void) | ||
| + | { | ||
| + | ShuffleArray(0, | ||
| + | } | ||
| + | </ | ||
| + | |||
| + | |||