Senior
It is required to implement the function uniqRandn, which generates a slice of length n of unique, random numbers. func main() { fmt.Println(uniqRandn(10)) } func uniqRandn(n int) []int { //... }
sobes.tech AI
Answer from AI
To generate a slice of n unique random numbers, you can use the following approach:
- Create a slice with numbers from 0 to m-1, where m >= n (for example, m = 2*n or more to have enough unique numbers).
- Shuffle the slice randomly.
- Take the first n elements.
Example implementation in Go:
package main
import (
"fmt"
"math/rand"
"time"
)
func uniqRandn(n int) []int {
m := n * 2 // you can increase this if you need a larger range
nums := make([]int, m)
for i := 0; i < m; i++ {
nums[i] = i
}
rand.Seed(time.Now().UnixNano())
rand.Shuffle(m, func(i, j int) {
nums[i], nums[j] = nums[j], nums[i]
})
return nums[:n]
}
func main() {
fmt.Println(uniqRandn(10))
}
If you need a range of numbers different from 0..m-1, you can adjust the generation of the initial slice. This approach guarantees uniqueness and randomness without repeats.