Hi,
I have just solved the community puzzle “Minimal number of swaps” in both Java and OCaml. However, regarding the OCaml version, I struggled a bit because the default sample of code (that is proposed right as one starts this puzzle) does not correctly parse the input. I give a fix below (but no spoiler regarding the puzzle solution).
Indeed, the code sample that is given initially uses the sscanf
function which applies to a string, and thus does not “consume” the input. The result is that the first number of the input is read 5 times (instead of reading each of the 5 numbers). In other words, the parsing returns 1 1 1 1 1
instead of the expected list 1 0 1 0 1
as given in the example.
Here is my replacement solution:
let n = int_of_string (input_line stdin) in
let line = Scanf.Scanning.from_string (input_line stdin) in
for i = 0 to n - 1 do
let x = Scanf.bscanf line "%d " (fun x -> (x)) in
();
done;
The changes are the following:
- The
line
variable is not of typestring
anymore but converted to anin_channel
(which is a buffer); - The
sscanf
function is replaced bybscanf
which reads buffers; - A space is added at the end of the format string:
"%d "
.
This was my first puzzle solving in OCaml so I didn’t check if this mistake occurs elsewhere.
Take care.