Skip to content

Commit

Permalink
Add ArrayShuffle
Browse files Browse the repository at this point in the history
  • Loading branch information
Vince0789 committed Feb 20, 2023
1 parent 6799faf commit f17373d
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 4 deletions.
8 changes: 4 additions & 4 deletions .vscode/tasks.json
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@
{
"label": "build only",
"type": "shell",
"command": "sampctl package build",
"command": "sampctl build",
"group": {
"kind": "build",
"isDefault": true
Expand All @@ -19,7 +19,7 @@
{
"label": "build watcher",
"type": "shell",
"command": "sampctl package build --watch",
"command": "sampctl build --watch",
"group": "build",
"isBackground": true,
"presentation": {
Expand All @@ -31,7 +31,7 @@
{
"label": "run tests",
"type": "shell",
"command": "sampctl package run",
"command": "sampctl run",
"group": {
"kind": "test",
"isDefault": true
Expand All @@ -46,7 +46,7 @@
{
"label": "run tests watcher",
"type": "shell",
"command": "sampctl package run --watch",
"command": "sampctl run --watch",
"group": "test",
"isBackground": true,
"presentation": {
Expand Down
21 changes: 21 additions & 0 deletions array_util.inc
Original file line number Diff line number Diff line change
Expand Up @@ -169,5 +169,26 @@ stock array_sort(array[], left = 0, right = sizeof array)
ArraySort(array, left, right);
}

/**
* <summary>
* Shuffles an array, using the Fisher-Yates algorithm.
* </summary>
* <param name="array">The array to shuffle.</param>
* <param name="size">Size of the array.</param>
* <remarks>
* Caution! Do not pass a string into this function. Doing so will corrupt it
* because the NUL terminator is moved to a different position in the array.
* </remarks>
*/
stock ArrayShuffle(array[], size = sizeof array)
{
for (new i = size - 1; i > 0; i--)
{
new j = random(i + 1);
new tmp = array[j];
array[j] = array[i];
array[i] = tmp;
}
}
// -----------------------------------------------------------------------------
// EOF
17 changes: 17 additions & 0 deletions test.pwn
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ main()
TestUnshift();
TestInArray();
TestSort();
TestShuffle();
}

TestShift()
Expand Down Expand Up @@ -78,6 +79,22 @@ TestSort()
PrintArray(arrayToSort);
}

TestShuffle()
{
printf("\nArrayShuffle");
printf("------------");

new arrayToShuffle[] = {13, 92, 85, 64, 17, 55, 33, 60, 58, 95};

printf("before shuffle:");
PrintArray(arrayToShuffle);

ArrayShuffle(arrayToShuffle);

printf("after sort:");
PrintArray(arrayToShuffle);
}

PrintArray(const arr[], size = sizeof arr)
{
new output[128];
Expand Down

0 comments on commit f17373d

Please sign in to comment.