(* I'd previously written this in Perl, but I didn't have the Perl
   version handy when I wanted to shuffle Bea's MP3 library through
   mplayer:
     find "$1" -name "*.mp3" | /home/kragen/bin/unsort | \
     while read song ; do /home/kragen/bin/mplayer "$song" < /dev/tty ; done
 *)

(* randomly reorder the lines in a short file given on stdin *)
(* my first useful OCaml program *)
(* I wonder if there's an efficient way to randomly shuffle a list 
   without mutation? *)

let randomly_reordered lines = 
    let result = Array.of_list lines in
    for i = Array.length result - 1 downto 0 do
        let other = Random.int (i + 1) and tmp = result.(i) in
        result.(i) <- result.(other) ; result.(other) <- tmp
    done; Array.to_list result
let rec input_lines () = 
    try let line = read_line ()
        in line :: (input_lines ())
    with End_of_file -> []
;;
Random.self_init () ;
List.iter print_endline (randomly_reordered (input_lines())) ;;

Reply via email to