Groups | Search | Server Info | Keyboard shortcuts | Login | Register [http] [https] [nntp] [nntps]


Groups > comp.soft-sys.math.mathematica > #13935 > unrolled thread

Re: Table with condition

Started byBill Rowe <readnews@sbcglobal.net>
First post2013-03-26 08:05 +0000
Last post2013-03-26 08:05 +0000
Articles 1 — 1 participant

Back to article view | Back to comp.soft-sys.math.mathematica


Contents

  Re: Table with condition Bill Rowe <readnews@sbcglobal.net> - 2013-03-26 08:05 +0000

#13935 — Re: Table with condition

FromBill Rowe <readnews@sbcglobal.net>
Date2013-03-26 08:05 +0000
SubjectRe: Table with condition
Message-ID<kirksd$ath$1@smc.vnet.net>
On 3/24/13 at 11:23 PM, Serych@panska.cz wrote:

>Dear mathgroup, I need to start creating list and continue until
>some condition is not met.  For example to generate list of random
>numbers until the value is not 5. Yes, it is theoreticaly possible
>to generate list with sufficient length, and cut it on the right
>place afterwords, but it is very inefficient way if the computation
>is much harder than just generation of random numbers.

>TakeWhile[Table[RandomInteger[{0, 10}], {15}], # != 5 &]

>Using the while cycle is the other way, but I can only print values
>using that method, but I don't know, how to generate classical list:

>r = 0; While[r != 5, r = RandomInteger[{0, 10}]; Print[r]]

>What is the right solution of such a simple problem?

What you might want to use is NestWhileList. Using your example
of RandomInteger you could do it as:

In[9]:= Most@
  NestWhileList[(#; RandomInteger[{0, 10}]) &,
   RandomInteger[{0, 10}], (# != 5) &]

Out[9]= {4,8,10,3,9,6,4,0,6,3,2,1,7,7,4,8,3,2}

What might be more efficient when each result really doesn't
depend on the previous result could be something like:

In[16]:= list = {}; r = 0;
While[r != 5, list = {list, r = RandomInteger[{0, 10}]}];
Most@Flatten[list]

Out[18]= {2,9,9,0,6,4,0,0,7,7,4,7}

Note, the issue of whether to generate a list of random integers
then use TakeWhile isn't just a question of efficiency. No
matter what length list you generate, there is always some
probability of it not having a 5. By pre-selecting the list
length you eliminate the possibility of having longer lists
which could occur.

[toc] | [standalone]


Back to top | Article view | comp.soft-sys.math.mathematica


csiph-web