Reputation: 25
I am trying to build a matrix in OCaml consisting only of 1 and 0. My current code is
let myArray = Array.make_matrix num num2 (Random.int 2) in
print myArray
However this fills the entire array up with only 0 or only 1, and not a combination, is there a way for me to do what i want?
Upvotes: 0
Views: 375
Reputation: 66823
Yes, Array.make_matrix
fills the matrix with a single value that you supply.
You can write this:
let myArray =
Array.init num
(fun _ -> Array.init num2 (fun _ -> Random.int 2))
Here's how it looks:
# let num = 2;;
val num : int = 2
# let num2 = 3;;
val num2 : int = 3
# let myArray =
Array.init num
(fun _ -> Array.init num2 (fun _ -> Random.int 2));;
val myArray : int array array = [|[|0; 1; 0|]; [|1; 1; 0|]|]
#
Update
If you want different numbers each time, you need to initialize the random number generator with a different seed each time. An easy way to do this is:
Random.self_init ()
You can call this once at program startup, and you'll get different random numbers in each run of the program.
Upvotes: 3