-2

How to pick the random value from slice in golang and i need to display it to cli.I have string which i converted to string array by splitting it. Now i want to choose random string from string array and display to user in cli and i need to ask user to input that particular string which is displayed on screen and compare the user entered input.

 string randgen := ‘na gd tg er dd wq ff  gen  vf ws’
 s:= String.split(randgen,””)
 s = [“na”, “gd”, ”er”, “tg”, “er”, “dd”, “wq”, “ff”, “gen”, “vf”, “ws”]
Nagaraj M
  • 387
  • 1
  • 5
  • 16

1 Answers1

1

There are some issues with your code. You shouldn't define the type when initializing a variable using :=.

Also, it's not recommended to depend on spaces to construct and split your slice, as it's not clear what will happen if for example you have multiple spaces, or a tab between the characters instead.

This is a minimal solution that 'just works'.

package main

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

func main() {
        randgen := `na gd tg er dd wq ff gen vf ws`
        s := strings.Split(randgen, " ")
        fmt.Println(s)

        rand.Seed(time.Now().UnixNano())
        randIdx := rand.Intn(len(s))

        fmt.Println("Randomly selected slice value : ", s[randIdx])
}

I would suggest reading the rand package documentation for an explanation of what rand.Seed does. Also, take a look at the shuffle function available in rand, as it's suited to your problem, if you want to build a more robust solution.

hyperTrashPanda
  • 838
  • 5
  • 18
  • thank you, i tried above code, it choose the first letter from the slice. – Nagaraj M Jul 04 '19 at 12:14
  • Each time you run it, it will choose and print a different item in the slice. Eg. in the first run it might choose and print `dd`, the second time `na` and one third time `gen`. Is this what you'd expect? Run it locally, as the Go Playground has an issue with `rand` because time is constant. – hyperTrashPanda Jul 04 '19 at 12:17