Weighted Random
Weighted random selection — pick a key from a weighted map with probability proportional to each entry’s float weight.
Categories:
RandomUtils (GS_Core::RandomUtils) provides a single templated static method for weighted random selection from a map. The caller provides their own AZ::SimpleLcgRandom instance for deterministic control over the random sequence.
Used by: RandomNodeData (dialogue random node), KlattVoiceComponent (phoneme selection), any system needing weighted random draws.
For usage guides and setup examples, see The Basics: GS_Core.
Contents
API Reference
template<typename T>
static T GetRandomWeighted(
AZ::SimpleLcgRandom* rand,
const AZStd::unordered_map<T, float>& weightedTable
);
Selects one key from weightedTable with probability proportional to its float weight value. Higher weights mean higher probability of selection.
| Parameter | Description |
|---|---|
rand | Caller-owned AZ::SimpleLcgRandom instance. The caller controls seeding and lifetime. |
weightedTable | Map of candidates to weights. Keys are the items to select from; values are their relative weights. |
Returns: The selected key of type T.
Edge cases:
- Falls back to the last entry on floating-point precision edge cases.
- Asserts if
weightedTableis empty.
Usage Example
#include <GS_Core/Utility/Random/RandomUtils.h>
#include <AzCore/Math/Random.h>
// Member field — keep the random instance alive across calls
AZ::SimpleLcgRandom m_random;
// Build a weighted table: key = item, value = relative weight
AZStd::unordered_map<AZStd::string, float> lootTable;
lootTable["Common Sword"] = 50.0f;
lootTable["Rare Shield"] = 30.0f;
lootTable["Epic Helmet"] = 15.0f;
lootTable["Legendary Ring"] = 5.0f;
// Select an item — "Common Sword" is 10x more likely than "Legendary Ring"
AZStd::string selected = GS_Core::RandomUtils::GetRandomWeighted(&m_random, lootTable);
See Also
For related resources:
Get GS_Core
GS_Core — Explore this gem on the product page and add it to your project.