RE: choose with replacement
- To: mathgroup@smc.vnet.net
- Subject: [mg10840] RE: [mg10800] choose with replacement
- From: Ersek_Ted%PAX1A@mr.nawcad.navy.mil
- Date: Tue, 10 Feb 1998 21:01:50 -0500
Dan wrote:
----------
|Simply put, I want to make a new list from an existing finite list by
|randomly choosing an element from list_1 to be included in list_2.
|List_1 would loose that element, and the random number generator would
|be reduced to correspond to the new length of the old list_1. This
|process would continue untill list_1 has no elements, and list_2 has
|all the elements of list_1 reordered. |
Dan,
You could write a procedural function that would do this the way you
describe, but this is very inefficient. You may also be able to do it
using Fold or Nest, but the most efficient way is probably with use
of an optional argument for Sort. The optional argument is the
ordering function (see below).
In[1]:=
?Sort
"Sort[list] sorts the elements of list into canonical order. Sort[list,
p] \ sorts using the ordering function p."
Now I make a list
In[2]:=
lst={3,4,5,6,7,1,2,-2,-6};
In the following I make a new sorted list. I could have got the same
list using Sort[lst].
Ordering function (#1<#2)& means to sort the terms with increasing
order.
In[3]:=
sorted=Sort[lst,(#1<#2)&]
Out[3]=
{-6,-2,1,2,3,4,5,6,7}
Ordering function (#1>#2)& means to sort the terms with decreasing
order.
In[4]:=
Sort[lst,(#1>#2)&]
Out[4]=
{7,6,5,4,3,2,1,-2,-6}
Ordering function (Random[Integer,1]==1)& has the effect of making a
random order.
Note: Random[Integer,n] is a random integer from {0,1,2, ..... , n}.
Random[Integer,1] can be either (0 or 1). Now I shuffle the
sorted list.
In[5]:=
Sort[sorted, (Random[Integer,1]==1)&]
Out[5]=
{-6,1,5,6,4,2,7,-2,3}
OK
Now lets try a list that has non-numeric elements.
In[6]:=
lst={1,2,3,a,b,c,d,e,f};
Sort[lst,(Random[Integer,1]==1)&]
Out[6]=
{f,b,1,c,3,2,a,e,d}
It still works.
You can do all sorts of things with the ordering function. Members of
this group can explain further if you are interested.
Ted Ersek