'How can i get an random value out of an array in OCaml
I have the function
let init_color() : t_color t_array =
{len = 7 ; value = [|blue ; red ; green ; yellow ; cyan ; magenta ; grey|]}
In OCaml and I'm trying to get a random value(color) of of it with another function. And im kinda struggling to do it, new to coding so il be glad to get some help.
Solution 1:[1]
To get a random number between zero (inclusive) and bound (exclusive), use Random.int bound, e.g.,
let random_color {len; colors} =
colors.(Random.int len)
or, for the normal builtin array type,
let random_element elements =
elements.(Random.int (Array.length elements))
P.S. there is no need to store the size of an array together with the array as it is already stored in the array, so Array.length is an O(1) operation.
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 |
