Mathematica 9 is now available
Services & Resources / Wolfram Forums
-----
 /
MathGroup Archive
1998
*January
*February
*March
*April
*May
*June
*July
*August
*September
*October
*November
*December
*Archive Index
*Ask about this page
*Print this page
*Give us feedback
*Sign up for the Wolfram Insider

MathGroup Archive 1998

[Date Index] [Thread Index] [Author Index]

Search the Archive

RE: choose with replacement




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




  • Prev by Date: ListPlot and List problem
  • Next by Date: Re: set manipulation
  • Prev by thread: Re: choose with replacement
  • Next by thread: RE: choose with replacement