How to generate a random number in vlang?

391 views Asked by At

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 ?

2

There are 2 answers

0
jh316 On BEST ANSWER

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..

2
depperm On

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)