How to select N unique random indices from an existing slice in Go

1 Answer

0 votes
package main

import (
    "fmt"
    "math/rand"
    "time"
)

/*
    Select N unique random indices from an existing slice in Go.
    Return the indices and print both the index and the corresponding value.

    Approach:
    - Build a slice 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.
*/

// shuffleIndices performs an in-place Fisher–Yates shuffle.
func shuffleIndices(indices []int) {
    for i := len(indices) - 1; i > 0; i-- {
        j := rand.Intn(i + 1) // random index in [0..i]
        indices[i], indices[j] = indices[j], indices[i]
    }
}

// pickUniqueIndices returns N unique random indices.
func pickUniqueIndices(arraySize int, count int) []int {
    if count > arraySize {
        panic("Cannot pick more unique indices than array size.")
    }

    // Build index slice
    indices := make([]int, arraySize)
    for i := 0; i < arraySize; i++ {
        indices[i] = i
    }

    // Shuffle them
    shuffleIndices(indices)

    // Return first N indices
    return indices[:count]
}

func main() {
    rand.Seed(time.Now().UnixNano()) // seed RNG

    // Example slice
    data := []int{5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6}

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

    // Get unique random indices
    indices := pickUniqueIndices(len(data), N)

    // Print results
    fmt.Println("Random unique indices and their values:")
    for _, idx := range indices {
        fmt.Printf("index %d -> value %d\n", idx, data[idx])
    }
}


/*
run:

Random unique indices and their values:
index 15 -> value 90
index 8 -> value 58
index 10 -> value 17
index 14 -> value 83
index 13 -> value 74
index 5 -> value 33

*/

 



answered Sep 12 by avibootz

Related questions

...