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


Groups > comp.soft-sys.math.mathematica > #13929

Re: Table with condition

Path csiph.com!usenet.pasdenom.info!goblin1!goblin.stu.neva.ru!uio.no!news.stupi.se!newspump.sol.net!posts.news.twtelecom.net!nnrp3.twtelecom.net!not-for-mail
From Bob Hanlon <hanlonr357@gmail.com>
Newsgroups comp.soft-sys.math.mathematica
Subject Re: Table with condition
Date Tue, 26 Mar 2013 08:05:01 +0000 (UTC)
Sender steve@smc.vnet.net
Approved Steven M. Christensen <steve@smc.vnet.net>, Moderator
Message-ID <kirkrd$asp$1@smc.vnet.net> (permalink)
References <20130325032310.11A0569D2@smc.vnet.net>
Lines 40
Organization Time-Warner Telecom
NNTP-Posting-Date 26 Mar 2013 08:05:26 GMT
NNTP-Posting-Host 6f6dddb7.news.twtelecom.net
X-Trace DXC=g\3[Z53<4X\=W9SRB>9:nQC_A=>8kQj6]9BHNOcEA\@Y83l0Va>C<FQEFiONJ7[GoV\07]\mK4>[S
X-Complaints-To abuse@twtelecom.net
Xref csiph.com comp.soft-sys.math.mathematica:13929

Show key headers only | View raw


Module[{ri, list},
 list = {ri = RandomInteger[10]};
 While[ri != 5, AppendTo[list, ri = RandomInteger[10]]];
 list]

{2, 2, 5}

AppendTo is fairly inefficient. If the condition is such that the list
is likely to be very long, the following may be a better approach:

Module[{ri, list},
 list = {ri = RandomInteger[10]};
 While[ri != 5, list = {list, ri = RandomInteger[10]}];
 list // Flatten]

{2, 8, 2, 10, 6, 2, 6, 5}


Bob Hanlon


On Sun, Mar 24, 2013 at 11:23 PM, =C5 er=C3=BDch Jakub <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?
>
> Thanks in advance for any help
>
> Jakub
>
>

Back to comp.soft-sys.math.mathematica | Previous | Next | Find similar | Unroll thread


Thread

Re: Table with condition Bob Hanlon <hanlonr357@gmail.com> - 2013-03-26 08:05 +0000

csiph-web