Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

While loop in Mathematica: multiple outputs

I have worked on a random number generator in Mathematica, suppressed by a number of conditions. Right now my code looks like this:

list = RandomSample[Range[36], 7];
f := If[1 <= Count[Select[list, # <= 12 &], _Integer] <= 2,
  If[Count[Select[list, # > 31 &], _Integer] >= 1,
   If[Count[Select[list, Divisible[#, {2, 7}] &], _Integer] <= 3, 
    Sort[list], False], False], False]
While[f == False,
  list = RandomSample[Range[36], 7];
  If[list == f, f]];
f

It is build up like this:

  1. A random list of 7 integers of the interval 1-36 is made
  2. f defines some conditions that have to be met: at least one and at most two elements in the range 1-12. At least one element greater than 31. At most 3 elements can be divisible be the integers in the range 2-7.
  3. If the conditions are met, f equals the list, False otherwise.
  4. Next thing is the "While" loop. If f is False, then a new list i generated, and this loop continues until f i no longer False.
  5. The result stored in f is called.

The thing is now: this only produces one line of output. I am interested in getting multiple outputs, e.g. 5-10. I have tried to do it in some way with the Table command, but the thing is that nothing defines both the function f and the while loop at the same time. So, by running table on f, I only get the same result a lot of times.

Any input on how to proceed here?

like image 272
thesixmax Avatar asked Dec 06 '25 10:12

thesixmax


1 Answers

I don't think the third line in your definition of f is doing what you think it's doing. Consider for example

Divisible[20, {2, 7}]

which returns {True, False}, not either True or False. This means that Select[list, Divisible[#, {2, 7}] &] will always return an empty list and Count[Select[list, Divisible[#, {2, 7}] &], _Integer] will always return 0.

If I interpret the conditions for the lists correctly, you could instead use something like

Count[Select[list, Or @@ Divisible[#, Range[2, 7]] &], _Integer] <= 3

With this and Alexy's suggestion to use Sow and Reap, you could do something like

f[list_] := And[
  1 <= Count[Select[list, # <= 12 &], _Integer] <= 2, 
  Count[Select[list, # > 31 &], _Integer] >= 1, 
  Count[Select[list, Or @@ Divisible[#, Range[2, 7]] &], _Integer] <= 3]

Block[{n = 0, list},
  Reap[While[n < 5, list = Sort@RandomSample[Range[36], 7]; 
    If[f[list], n++; Sow[list]]]]][[2, 1]]
like image 54
Heike Avatar answered Dec 08 '25 22:12

Heike



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!