Welcome to collectivesolver - Programming & Software Q&A with code examples. A website with trusted programming answers. All programs are tested and work.

Contact: aviboots(AT)netvision.net.il

Buy a domain name - Register cheap domain names from $0.99 - Namecheap

Scalable Hosting That Grows With You

Secure & Reliable Web Hosting, Free Domain, Free SSL, 1-Click WordPress Install, Expert 24/7 Support

Semrush - keyword research tool

Boost your online presence with premium web hosting and servers

Disclosure: My content contains affiliate links.

39,851 questions

51,772 answers

573 users

How to pick a random value from a map in Go

2 Answers

0 votes
package main

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

// Function to get a random value from a map
func getRandomValue(inputMap map[int]string) string {
    values := make([]string, 0, len(inputMap))
    
    for _, v := range inputMap {
        values = append(values, v)
    }
    
    randomIndex := rand.Intn(len(values))
    
    return values[randomIndex]
}

func main() {
    // Seed the random number generator
    rand.Seed(time.Now().Unix())

    // Initialize the map
    myMap := map[int]string{
        1: "C++",
        2: "C",
        3: "Java",
        4: "C#",
        5: "Rust",
        6: "Go",
        7: "Python",
    }

    // Get a random value
    randomValue := getRandomValue(myMap)
    fmt.Println("Random value:", randomValue)
}


/*
run:

Random value: C#

*/

 



answered Jul 16, 2025 by avibootz
0 votes
package main

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

// Function to get a random value from a map
func getRandomValue(inputMap map[int]string) string {
    rnd := rand.Intn(len(inputMap))
	
	for _, val := range inputMap {
		if rnd == 0 {
			return val
		}
		rnd--
	}
	
	panic("unreachable")
}

func main() {
    // Seed the random number generator
    rand.Seed(time.Now().Unix())

    // Initialize the map
    myMap := map[int]string{
        1: "C++",
        2: "C",
        3: "Java",
        4: "C#",
        5: "Rust",
        6: "Go",
        7: "Python",
    }

    // Get a random value
    randomValue := getRandomValue(myMap)
    fmt.Println("Random value:", randomValue)
}



/*
run:

Random value: Java

*/

 



answered Jul 16, 2025 by avibootz

Related questions

1 answer 58 views
1 answer 66 views
1 answer 60 views
60 views asked Aug 7, 2025 by avibootz
1 answer 183 views
1 answer 61 views
...