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

1 Answer

0 votes
import Foundation

/*
    Select N unique random indices from an existing array in Swift.
    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 shuffled() (Fisher–Yates internally).
    - Take the first N shuffled indices — guaranteed unique.
    - Return those indices to the caller.
*/

/** Return N unique random indices */
func pickUniqueIndices(arraySize: Int, count: Int) -> [Int] {
    if count > arraySize {
        fatalError("Cannot pick more unique indices than array size.")
    }

    // Build index list
    let indices: [Int] = Array(0..<arraySize)

    // Shuffle and take first N
    return Array(indices.shuffled().prefix(count))
}

func main() {
    // Example array
    let data: [Int] = [5, 12, 5, 19, 5, 33, 47, 5, 58, 61, 17, 3, 5, 74, 83, 90, 6]

    let n: Int = 6 // number of unique indices to pick

    // Get unique random indices
    let indices: [Int] = pickUniqueIndices(arraySize: data.count, count: n)

    // Print results
    print("Random unique indices and their values:")
    for idx in indices {
        print("index \(idx) -> value \(data[idx])")
    }
}

main()


/*
run:

Random unique indices and their values:
index 4 -> value 5
index 15 -> value 90
index 12 -> value 5
index 16 -> value 6
index 1 -> value 12
index 0 -> value 5

*/

 



answered Sep 12 by avibootz

Related questions

...