Search All of the Math Forum:

Views expressed in these public forums are not endorsed by NCTM or The Math Forum.

Notice: We are no longer accepting new posts, but the forums will continue to be readable.

Topic: Table with condition
Replies: 2   Last Post: Mar 26, 2013 4:05 AM

 Search Thread: Advanced Search

 Messages: [ Previous | Next ]
 Bob Hanlon Posts: 906 Registered: 10/29/11
Re: Table with condition
Posted: Mar 26, 2013 4:05 AM
 Plain Text Reply

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
>
>

Date Subject Author
3/26/13 Bob Hanlon
3/26/13 Sseziwa Mukasa

© The Math Forum at NCTM 1994-2018. All Rights Reserved.