Senior
Implement a uniqRandn function that generates a slice of length n with unique, random numbers. import ( "fmt" "math/rand" ) 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 approach of shuffling a slice of numbers from 0 to the maximum value and taking the first n elements. For example:
import (
"fmt"
"math/rand"
"time"
)
func uniqRandn(n int) []int {
// Create a slice with numbers from 0 to n-1
nums := make([]int, n)
for i := 0; i < n; i++ {
nums[i] = i
}
// Shuffle the slice
rand.Seed(time.Now().UnixNano())
rand.Shuffle(n, func(i, j int) {
nums[i], nums[j] = nums[j], nums[i]
})
return nums
}
func main() {
fmt.Println(uniqRandn(10))
}
If you need unique numbers in another range, for example from 0 to m-1, where m >= n, you can create a slice of length m and take the first n elements after shuffling.