From 4951d8af992b06b052cc28f9e98891c8b869061f Mon Sep 17 00:00:00 2001 From: ghoulslash <41651341+ghoulslash@users.noreply.github.com> Date: Wed, 7 Apr 2021 09:56:57 -0600 Subject: [PATCH] Created Uniquely Shuffle Array (markdown) --- Uniquely-Shuffle-Array.md | 58 +++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 Uniquely-Shuffle-Array.md diff --git a/Uniquely-Shuffle-Array.md b/Uniquely-Shuffle-Array.md new file mode 100644 index 0000000..e6f0e1a --- /dev/null +++ b/Uniquely-Shuffle-Array.md @@ -0,0 +1,58 @@ +## Uniquely Shuffle Array + +credits to ghoulslash + +This function is useful for internal randomizers or other challenges. It allows us to uniquely shuffle a predefined array of values (e.g. species) using the [Fisher-Yates algorithm](https://en.wikipedia.org/wiki/Fisher%E2%80%93Yates_shuffle) + +### The Function +```c +/* +Inputs: + list: array of u16 values + count: size of the array (or number of elements to shuffle) +*/ +void ShuffleList(u16 *list, u16 count) +{ + u16 i; + + for (i = (count - 1); i > 0; i--) + { + u16 j = Random() % (i + 1); + u16 arr = list[j]; + list[j] = list[i]; + list[i] = arr; + } +} +``` + +### Example +In this example, we will shuffle all possible starters through gen 3 + +static const u16 sSpeciesToRandomize[9] = { + SPECIES_BULBASAUR, + SPECIES_CHARMANDER, + SPECIES_SQUIRTLE, + SPECIES_CHIKORITA, + SPECIES_CYNDAQUIL, + SPECIES_TOTODILE, + SPECIES_TREECKO, + SPECIES_TORCHIC, + SPECIES_MUDKIP +}; + +// obviously, this is a terrible way to choose a random starter, but is a good example of how to use the shuffling algorithm. +// we cannot write to `const` data, so we must copy it to EWRAM first. +```c +EWRAM_DATA static u16 sStarters[9] = {0}; +static u16 ChooseStarter(void) +{ + memcpy(sStarters, sSpeciesToRandomize, sizeof(sSpeciesToRandomize)); + ShuffleList(sStarters, NELEMS(sSpeciesToRandomize)); + + StringCopy(gStringVar1, gSpeciesNames[sStarters[0]]); // buffer the chosen species' name + return sStarters[0]; // return the first element of the now randomized list, sSpeciesToRandomize +} +``` + + +