3
$\begingroup$

I saw this uses $, but it was not clear what does it do there.

Table[Image3D@   Array[Boole@      FreeQ[Plus @@        Mod[PadLeft@IntegerDigits[{##} - 1, 3], 2, 1], $ | ## & @@        s] &, {3, 3, 3}^3], {s, Subsets@{3, 4, 5, 6}}]

Tried

?$
??$

Neither gives any information. Initially I thought it was a typo, but it's not.

enter image description here

$\endgroup$
1
  • $\begingroup$ I agree with Henrik that this appears to be a shorthand for applying Alternatives. I like terse code so I appreciate the attempt but it can be done better and safer: # | ##2 & @@ s. Or, if playing "code-golf" save an extra character with #|##&@@s as the duplicated first element has little effect. $\endgroup$
    – Mr.Wizard
    Commented Jul 24, 2018 at 10:27

1 Answer 1

7
$\begingroup$

Dollars have no built-in meaning. They can be used for variable names. Some global "constants" or settings have a leading $ (e.g. $HomeDirectory or $HistoryLength), somewhat by convention to distinguish them from other symbols. Moreover, Module appends $ and a ever increasing number to its variable names in order to make them unique (see also Unique).

In this particular case $ is just used as something that will certainly not show up. It's a hack. And a bad one because it introduces things in the code that need not be there. I guess it was meant for some kind of code golfing.

The following code would be a bit less obfuscating and does the same:

Table[
 Image3D@Array[
  Boole@FreeQ[
   Total @ Mod[PadLeft@IntegerDigits[{##} - 1, 3], 2, 1], 
   Alternatives @@ s
  ] &, 
  {3, 3, 3}^3
  ], 
 {s,Subsets@{3, 4, 5, 6}}
 ]

Edit

By the way, here is some code that does the same but in a vectorized way, and thus, several hundred times faster:

k = 3;
AbsoluteTiming[
 d = Mod[Developer`ToPackedArray[PadLeft[IntegerDigits[Range[0, 3^k - 1], 3]]], 2, 1];
 b = Outer[Plus, d, d, d, 1];
 img = Table[
   Image3D@Threshold[
     ArrayReshape[
       Normal[SparseArray[Partition[s, 1] -> 0., {9}, 1.]][[Flatten[b]]],
       Dimensions[b]
       ].ConstantArray[1./Dimensions[d][[2]], Dimensions[d][[2]]],
     1 - $MachineEpsilon
     ],
   {s, Subsets[{3, 4, 5, 6}]}
   ];
 ]

0.010862

The original code takes about 4.34 seconds on my machine.

$\endgroup$

Not the answer you're looking for? Browse other questions tagged or ask your own question.