Implémentations pratiques
Scénarios de génération de nombres aléatoires dans le monde réel
1. Génération d'entiers aléatoires
package main
import (
"fmt"
"math/rand"
"time"
)
func generateRandomInteger(min, max int) int {
rand.Seed(time.Now().UnixNano())
return rand.Intn(max - min + 1) + min
}
func main() {
// Generate random number between 1 and 100
randomNumber := generateRandomInteger(1, 100)
fmt.Println("Random Number:", randomNumber)
}
2. Sélection aléatoire dans un slice
func selectRandomItem(items []string) string {
rand.Seed(time.Now().UnixNano())
return items[rand.Intn(len(items))]
}
func main() {
fruits := []string{"Apple", "Banana", "Cherry", "Date"}
randomFruit := selectRandomItem(fruits)
fmt.Println("Random Fruit:", randomFruit)
}
Cas d'utilisation de la randomisation
graph TD
A[Randomization Applications]
A --> B[Game Development]
A --> C[Scientific Simulations]
A --> D[Security Testing]
A --> E[Machine Learning]
Génération aléatoire sécurisée
Nombres aléatoires cryptographiquement sécurisés
package main
import (
"crypto/rand"
"fmt"
"math/big"
)
func secureRandomNumber(max int64) (int64, error) {
n, err := rand.Int(rand.Reader, big.NewInt(max))
if err != nil {
return 0, err
}
return n.Int64(), nil
}
func main() {
randomNum, err := secureRandomNumber(1000)
if err != nil {
fmt.Println("Error generating secure random number")
return
}
fmt.Println("Secure Random Number:", randomNum)
}
Techniques de randomisation
Technique |
Cas d'utilisation |
Complexité |
Graine simple |
Randomisation de base |
Faible |
Graine basée sur le temps |
Séquences uniques |
Moyenne |
Graine cryptographique |
Haute sécurité |
Élevée |
Générateur aléatoire réutilisable
type RandomGenerator struct {
source rand.Source
rng *rand.Rand
}
func NewRandomGenerator() *RandomGenerator {
source := rand.NewSource(time.Now().UnixNano())
return &RandomGenerator{
source: source,
rng: rand.New(source),
}
}
func (r *RandomGenerator) RandomInt(min, max int) int {
return r.rng.Intn(max - min + 1) + min
}
Meilleures pratiques
- Initialisez toujours la graine avant de générer des nombres aléatoires
- Utilisez la technique de randomisation appropriée
- Prenez en compte les exigences de performance et de sécurité
- Exploitez les modèles recommandés par LabEx pour des implémentations robustes
Gestion des erreurs et validation
Mettez en œuvre des vérifications d'erreurs et des validations appropriées lors de la génération de nombres aléatoires pour garantir la fiabilité et éviter les comportements inattendus.