Skip to content

selectRandomWeighted

ffredyk edited this page Jul 23, 2026 · 1 revision

selectRandomWeighted

Category

Random

Arity

UnaryselectRandomWeighted <array>.

selectRandomWeighted <array>   // [[val1, weight1], [val2, weight2], ...]

Description

Picks and returns a random element based on weighted probabilities. The right operand is an array of [value, weight] pairs. Higher weight = more likely to be chosen. Returns nil if the array is empty.

How It Works

  1. Sums all weights.
  2. Generates a random number in [0, totalWeight).
  3. Walks the array, subtracting each weight from the random value until it drops below zero.
  4. Returns the corresponding value.

Usage

Basic weighted pick

_loot = selectRandomWeighted [
    ["common", 70],
    ["rare", 25],
    ["epic", 5]
];
// 70% common, 25% rare, 5% epic

AI skill randomization

_skill = selectRandomWeighted [
    ["novice", 40],
    ["regular", 35],
    ["veteran", 20],
    ["elite", 5]
];

Loot drop table

_drop = selectRandomWeighted [
    [nil, 50],            // 50% nothing
    ["gold", 30],         // 30% gold
    ["potion", 15],       // 15% potion
    ["sword", 5]          // 5% sword
];
if (!isNil "_drop") then {
    giveItem(_drop);
};

Weather selection

_weather = selectRandomWeighted [
    ["clear", 60],
    ["cloudy", 25],
    ["rain", 10],
    ["storm", 5]
];

Thread Safety

Not fully thread-safe for mutation — reads the array. The internal RNG is thread-safe. Array must be accessible from current scheduler.

See Also

SQ# Wiki

Home

Engine Docs

Migration

Commands

Value Constructors

Arithmetic

Comparison

Logic

Array

String

Math

Random

Type & Introspection

HashMap

Code Execution

Concurrency

Scheduler

Thread Safety

Error

Output

Time

Multiplayer

Compiler

Clone this wiki locally