Does Mathematica have a function similar to Table[...] but with an extra argument to specify a condition, such that terms are added to the generated list only if that condition is True?
Currently I apply Select after generating a Table, but that consumes too much memory because it generates a large list, most terms in which I do not need.
If instead I use Do[...] and check the condition for every term separately using If before adding it to the the list with AppendTo, the performance drops considerably, and the resulting code is longer than it needs to be.
I am surprized there is no version of the Table function that would take an extra condition, or maybe it is just called differently?
Apparently, the third option proposed by azerbajdzan is not always faster. I have now compared the following three codes, and the one with ## &[] actually wins!
Option 1:
CountNonCoprimes10[i_] := ParallelTable[ If[! CoprimeQ @@ #, #, ## &[]] &[{FromDigits[#], FromDigits[# /. {0 -> 1, 1 -> 0}]} &[ IntegerDigits[n, 2]]], {n, 2^(i - 1), 2^i - 1}] // Length; MaxMemoryUsed[CountNonCoprimes10[20]] // Timing Output: {5.1875, 17993160}
Option 2:
CountNonCoprimes10[i_] := ParallelTable[ If[! CoprimeQ @@ #, #, Nothing] &[{FromDigits[#], FromDigits[# /. {0 -> 1, 1 -> 0}]} &[ IntegerDigits[n, 2]]], {n, 2^(i - 1), 2^i - 1}] // Length; MaxMemoryUsed[CountNonCoprimes10[20]] // Timing Output: {5.84375, 17993288}
Option 3:
CountNonCoprimes10[i_] := Last@Last@ Reap@Do[If[! CoprimeQ @@ #, Sow@#] &[{FromDigits[#], FromDigits[# /. {0 -> 1, 1 -> 0}]} &[ IntegerDigits[n, 2]]], {n, 2^(i - 1), 2^i - 1}] // Length; MaxMemoryUsed[CountNonCoprimes10[20]] // Timing Output: {6.79688, 34961728}
So now the third option clearly loses the competition, but also here I am using the nonparallelized version of Do. Is there a way to make Sow work inside ParallelDo?
Table[If[i < 3, i, ## &[]], {i, 5}]is exactly what I need. $\endgroup$Table[If[i < 3, i, Nothing], {i, 5}]$\endgroup$Nothingdoes the same thing. Never too late to learn. $\endgroup$Nothingremoved from the list after the whole list is already created, or it is not added there at all? In other words, does a list with manyNothing's take more memory? I am now testing the version with## &[]insideParallelTable, and that's extremely quick. $\endgroup$