summaryrefslogtreecommitdiff
diff options
context:
space:
mode:
-rw-r--r--Uniquely-Shuffle-Array.md58
1 files changed, 58 insertions, 0 deletions
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
+}
+```
+
+<a href="https://imgur.com/qk4VFbF"><img src="https://imgur.com/qk4VFbF.gif" title="source: imgur.com" /></a>
+