BeginPackage["UVW`DiscSamp`"]
(* Version 2.0, 08/15/97 *)

Distribution::usage="Distribution[listofdata] returns a list of pairs. 
The first element of each pair is a value appearing in listofdata, 
the second one is the frequency of that value in listofdata."  
			       
RSPermutation::usage="RSPermutation[list,n] returns a list of n random 
permutations of list." 

RSExtract::usage="RSExtract[list,k,n] returns a list of n lists of length k, 
extracted at random from list."

RSDiscreteDistribution::usage="RSDiscreteDistribution[dist,n] returns a
random sample of size n of the distribution dist, given under the form of
a list of nonnegative reals. The list dist is first divided by 
its sum then interpreted as a probability distribution on the set 
{1,...,Length[dist]}."
			      
			       

Begin["`Private`"]

Distribution[list_List]:=

	 Block[{red,len,shortlen,i},

	      red = Union[list];
	      len = Length[list];
	      shortlen = Length[red];
	      Return[Table[{red[[i]],
			   N[Count[ list,red[[i]] ]/len]},
			   {i,shortlen}]
		    ];
	      ];


RSPermutation[list_List,n_Integer]:=

	    Block[{len,i,r,swap,perm,result={}},
		 len=Length[list];
		 Do[
		   perm=list;
		   For[i=1,i<len,i++,
			r=Random[Integer,{i,len}];
			swap=perm[[i]];
			perm[[i]]=perm[[r]];
			perm[[r]]=swap;
		       ];
		    result=Append[result,perm],
		   {n}];
		 Return[result];

		 ];

       

RSExtract[list_List,k_Integer,n_Integer]:=

	    Block[{r,listbool={},samp={},extr={},len},

		 len=Length[list];
		 Do[
		   (
		   listbool=Transpose[{list,Table[False,
						  {len}]}];
		   extr={};
		    
		   Do[
		     (
		     r=Random[Integer,{1,len}];
		     While[listbool[[r,2]],
			   r=Random[Integer,{1,len}]
			  ];
		     extr=Append[extr,listbool[[r,1]]];
		     listbool[[r,2]]=True
		     )
		     ,{k}];
		   extr = Sort[extr];
		   samp = Append[samp,extr]
		   )
		   ,{n}];
		   Return[samp];

		       ];


 
RSDiscreteDistribution[dist_List,n_Integer]:=

	    Block[{cumul={},j,choice,res={}},

		 If[VectorQ[dist],
			 (
		     cumul = N[dist];
		     cumul = cumul/Apply[Plus,cumul];
		     cumul = Rest[FoldList[Plus,0,cumul]];
		     Do[
			 (
			 choice=Random[];
			 j=1;
			 While[choice>cumul[[j]],
			       j=j+1];
			 res=Append[res,j]
			 )
		     ,{n}];
		     Return[res];
			) 
		    
		    ];
		 ];

		 
End[]


EndPackage[]

