Jaoa
Jaoa

Reputation: 95

Printing randomly from a list OCAML

How do I print each line in a text file only once but in a random order?

I have a text file that containts six individual lines and I am trying to print them to the screen randomly

Here is the code I have so far

open Scanf 
open Printf

let id x = x 
let const x = fun _ -> x
let read_line file = fscanf file "%s@\n" id 
let is_eof file = try fscanf file "%0c" (const false) with End_of_file -> true


let _ = 
  let file = open_in "text.txt" in 
  while not (is_eof file) do 
    let s = read_line file in
    printf "%s\n" s 
  done;

  close_in file

I could append elements "s" into a list. Printing elements in a list can be as simple as following however, I am not sure how to print elements in the list randomly.

let rec print_list = function 
[] -> ()
| e::l -> print_int e ; print_string " " ; print_list l

Upvotes: 0

Views: 99

Answers (1)

Pierre G.
Pierre G.

Reputation: 4425

let's define a function that retrieve one element identified by its position in a list, and return a tuple (this_element, the_list_wo_this_element).

Ex : pick [0;2;4;6;8] 3
returns (6, [0;2;4;8)).

Then, by iterating on the resulted list (the rhs of the tuple above), you pick a random element from that list , until that list is empty.

Upvotes: 0

Related Questions