'Print Bool matrix but replace true and false with 1's and 0's
I'm doing a task where I need to have a function printmat : bool array array -> unit = <fun> that
given a bool matrix it prints it on screen with ones and zeros, instead of
true and false.
So far, I only managed to print the already existing matrix with 1's and 0's and my first variable is a string instead of bool. I was just wondering how to change to code so I need to CALL the function and type in the bool array array instead of having the declared one?
let matrix = [|
[|true; true; false; false|];
[|false; false; true; true|];
[|true; false; true; false|];
[|true; false; false; true|]
|];;
let print_s matrix =
let n = Array.length matrix in
for i = 0 to n - 1 do
let n1 = Array.length matrix in
for j = 0 to n1 - 1 do
print_string matrix.(i).(j);
done;
print_string "/n";
done;;
Solution 1:[1]
You code already has a function, print_s, which you have to call something like this,
let example = [|
[|"1"; "0"|];
[|"0"; "1" |]
|]
print_s example;;
It will print something like
10/n01/n-
This indicates that your function has three problems:
- no separation between row elements
- missing new line (should be
"\n"not"/n") - wrong input type, you want
bool array arraybut it acceptsstring array array
To print a boolean value as a number, you can write a helper function and use it instead of print_string (which obviously accepts a string). You can use if/then/else to distinguish between two possible states of a bool variable. So if the boolean value is true, then you should print "1" else you should print "0".
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 | ivg |
