#!/usr/bin/env mash
(* A sample mathematica script -- the inverse of the 
   unix sort utility.
   If a number is specified as a command line argument,
   returns only that many of the lines.
   So this can be used like RandomKSubset for files.
   Example usage:  shuffle.m 3 < test.txt | sort
     Takes 3 random lines from test.txt and outputs 
     them in sorted order.
   (The functions readList, prn, perr, and eval are defined
    by mash.)
*)

(* FUNCTIONS ********************************************)

(* Shuffles a list. Inspired by RandomPermutation. *)
shuffle[l_List] := #2& @@@ Sort[{Random[],#}& /@ l]


(* MAIN *************************************************)

(* number of lines to output, specified on command line *)
numWanted = If[Length@ARGV<2, Infinity, eval[ARGV[[2]]]];

If[Length@ARGV>2, perr["Usage: ", ARGV[[1]], " [num of lines]\n";]];

(* gets a list of all the lines on stdin *)
lines = readList[];
numLines = Length@lines;

(* prints numWanted of them in random order to stdout *)
prn @@ Riffle[Take[shuffle@lines, Min[numLines, numWanted]], "\n"]; 
 
