Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Semrush - keyword research tool

Create your online store today with Shopify

Turn ChatGPT, Claude, Gemini, And CoPilot Into Your Personal Assistant, Business Coach, Content Creator, And More

AFFILIATE MARKETING Your all-in-one performance engine Manage affiliates, creators, and customer referrals in one unified platform—turning every partnership into measurable growth

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Disclosure: My content contains affiliate links.

43,226 questions

56,128 answers

573 users

How to select N unique random indices from an existing array in TypeScript

1 Answer

0 votes
/*
    Select N unique random indices from an existing array in TypeScript.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Build an array of indices: 0, 1, 2, ..., size-1.
    - Shuffle the indices using Fisher–Yates (efficient and predictable).
    - Take the first N shuffled indices — guaranteed unique.
    - Return those indices to the caller.
*/

/** Shuffle an array of indices using Fisher–Yates */
function shuffleIndices(indices: number[]): void {
    for (let i: number = indices.length - 1; i > 0; i--) {
        const j: number = Math.floor(Math.random() * (i + 1)); // random index in [0..i]
        const temp: number = indices[i];
        indices[i] = indices[j];
        indices[j] = temp;
    }
}

/** Return N unique random indices */
function pickUniqueIndices(arraySize: number, count: number): number[] {
    if (count > arraySize) {
        throw new Error("Cannot pick more unique indices than array size.");
    }

    // Build index list
    const indices: number[] = Array.from({ length: arraySize }, (_, i) => i);

    // Shuffle them
    shuffleIndices(indices);

    // Return first N indices
    return indices.slice(0, count);
}

// Example array
const data: number[] = [5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6];

const N: number = 6; // number of unique indices to pick

// Get unique random indices
const indices: number[] = pickUniqueIndices(data.length, N);

// Print results
console.log("Random unique indices and their values:");
for (const idx of indices) {
    console.log(`index ${idx} -> value ${data[idx]}`);
}


/*
run:

Random unique indices and their values:
index 7 -> value 5
index 11 -> value 3
index 2 -> value 5
index 9 -> value 61
index 15 -> value 90
index 14 -> value 83

*/

 



answered Sep 12 by avibootz
...