import { min2 } from "../../math/min2.js";
import { array_shuffle } from "./array_shuffle.js";

/**
 * Pick multiple random items from an array
 *
 * @template T
 * @param {function} random random function, must return a value between 0 and 1
 * @param {T[]} source Where to pick elements from
 * @param {T[]} target Where to place picked elements
 * @param {number} count how many items to pick, if this number is greater than the length of {@link source}, it will be limited to length of {@link source} instead
 * @returns {number} number of picked elements
 */
export function randomMultipleFromArray(random, source, target, count) {

    const order = [];

    const source_length = source.length;
    for (let i = 0; i < source_length; i++) {
        order[i] = i;
    }

    array_shuffle(random, order);

    const target_length = min2(source_length, count);

    for (let i = 0; i < target_length; i++) {
        const index = order[i];
        const element = source[index];
        target.push(element);
    }

    return target_length;
}
