'How to generate a random number in vlang?
I want to randomly pick an item in a array.Like javascript code
words[Math.floor(Math.random() * words.length)]
But I don't know how to generate a number like javascript Math.random() function in vlang. Does anyone know ?
Solution 1:[1]
Per the documentation at rand, you can use the rand module and for example, the rand.u32n(words.length) function. Make sure you handle the optional case..
Solution 2:[2]
There are a few ways
- use
choose
import rand
words := ['one', 'two', 'three']
word := rand.choose<string>(words, 1) or {[words[0]]} // this is a list
println(word[0])
- use
intn
import rand
words := ['one', 'two', 'three']
word := words[rand.intn(words.len) or {0}]
println(word)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | jh316 |
| Solution 2 | depperm |
