Basic Usage

You shouldn't need to read beyond this page in most cases since simple random weighted selection is mostly enough for stuff.

Simple Weighted Selection

const items = [
    { result: "SSR cool character", chance: 1 },
    { result: "Kinda rare character", chance: 3 },
    { result: "Mob character", chance: 5 },
    { result: "Mob character", chance: 5 },
    { result: "Mob character", chance: 5 },
];

GachaMachine.roll(items); // Rolls one item from the list of items.

You can speed up the rolling by supplying the total weight of the data (sum of all chances/weights).

GachaMachine.roll(items, 19); // Rolls one item from the list of items, faster.

Using other available algorithms

There is no reason to use any other available algorithm for random weighted selection but if you do need one, you can make use of the algorithms directory.

import { roll } from "https://deno.land/x/[email protected]/algorithms/v1.ts";

const items = [
    { result: "SSR cool character", chance: 1 },
    { result: "Kinda rare character", chance: 3 },
    { result: "Mob character", chance: 5 },
    { result: "Mob character", chance: 5 },
    { result: "Mob character", chance: 5 },
];

roll(items); // Rolls one item from the list of items but much slower.

You can compare the execution speed of algorithms by cloning the repo and using deno task bench.

Algorithm10 Rolls100k Rolls
v11.29 ms12.99 s
v278.34 µs763.47 ms
v324.59 µs245.98 ms
v4_sub24.5 µs240.8 ms
v422.86 µs228.56 ms
Edit this page on GitHub Updated at Thu, Aug 4, 2022