Sobes.tech
Middle+

It is required to implement the uniqRandn function, which generates a slice of length n of 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 following approach:

  • Create a slice with numbers from 0 to m (where m >= n, for example m = n*10 or another suitable value).
  • Shuffle the slice using the Fisher-Yates algorithm.
  • Take the first n elements.

If the range is unlimited, you can use a map to check for uniqueness, but this is less efficient.

Example implementation:

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

func uniqRandn(n int) []int {
	// Assume the range of numbers from 0 to n*10
	max := n * 10
	nums := make([]int, max)
	for i := 0; i < max; i++ {
		nums[i] = i
	}

	rand.Seed(time.Now().UnixNano())

	// Shuffle the slice
	for i := max - 1; i > 0; i-- {
		j := rand.Intn(i + 1)
		nums[i], nums[j] = nums[j], nums[i]
	}

	return nums[:n]
}

func main() {
	fmt.Println(uniqRandn(10))
}

This code guarantees the uniqueness of the numbers and their random order.