-
Notifications
You must be signed in to change notification settings - Fork 2.7k
Uniquely Shuffle Array
ghoulslash edited this page Apr 7, 2021
·
1 revision
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
/*
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;
}
}
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.
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
}