Error in the OCaml default code sample in “Minimal number of swaps” (community puzzle)


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

The changes are the following:

  • The line variable is not of type string anymore but converted to an in_channel (which is a buffer);
  • The sscanf function is replaced by bscanf 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.