Sobes.tech
Senior

Vajadzētu realizēt funkciju uniqRandn, kas ģenerē sarakstu ar n unikāliem, nejaušiem skaitļiem. import ( "fmt" "math/rand" ) func main() { fmt.Println(uniqRandn(10)) } func uniqRandn(n int) []int { //... }

sobes.tech AI

Vastus AI-lt

To generate a sample of n unique random numbers, you can use an approach where you shuffle a list of numbers from 0 to the maximum value and take the first n elements. For example:

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

func uniqRandn(n int) []int {
    // Create a list with numbers from 0 to n-1
    nums := make([]int, n)
    for i := 0; i < n; i++ {
        nums[i] = i
    }

    // Shuffle the list
    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 list of length m and take the first n elements after shuffling.