3
$\begingroup$

I want to make the digits from this output to print starting from the rightmost column.

Array[Function[n,IntegerDigits[n,2]],5] // ArrayPlot[#, ColorRules -> {0-> Gray, 1 -> Black}, Mesh-> True, Background->None, Frame-> False]&

The first three rows should be

None (*white square*), None (*white square*), 1 (*black square*)
None (*white square*), 1 (*black square*), 0 (*gray square*)
None (*white square*), 1 (*black square*), 1 (*black square*)

The default plot shows

  1 (*black square*), None, None
  1 (*black square*), 0 (*gray square*), None
  1 (*black square*), 1 (*black square*), None
  ...

enter image description here

$\endgroup$

2 Answers 2

4
$\begingroup$

Use PadLeft[]:

ArrayPlot[PadLeft[Array[Function[n, IntegerDigits[n, 2]], 5], Automatic, None],
          Background -> None, ColorRules -> {0 -> Gray, 1 -> Black},
          Frame -> False, Mesh -> True]

right-aligned

$\endgroup$
2
  • $\begingroup$ I came up with digits = Array[Function[n,IntegerDigits[n,2]],5]; pad = Max[Length /@ Array[Function[n,IntegerDigits[n,2]],5]]; paddedDigits = PadLeft[#, pad, None]& /@ digits; ArrayPlot[paddedDigits,ColorRules -> {0-> Gray, 1 -> Black, None-> White}, Mesh-> True ] before your posting. Your solution looks nicer. $\endgroup$ Commented Jul 28, 2016 at 4:46
  • $\begingroup$ @and, in general PadLeft[] and PadRight[], when applied to a ragged array, builds a rectangular array with the appropriate columns containing the padding element (taken to be 0 by default); in the case of PadLeft[arr, Automatic, None], the padding element used is None, which is then rendered appropriately by ArrayPlot[]. $\endgroup$ Commented Jul 28, 2016 at 4:48
3
$\begingroup$

Some magic for your entertainment:

Range[5] ~IntegerDigits~ 2 + 1 // 
  Block[{PadRight = PadLeft}, ArrayPlot[#, Mesh -> True]] &

enter image description here

$\endgroup$
2
  • $\begingroup$ A little spelunking should help with showing why this works. ;) $\endgroup$ Commented Jul 28, 2016 at 5:57
  • $\begingroup$ @J.M. It seemed logical that PadRight would be used to do the equivalent (but opposite) of what you did, and a Trace showed that it was. This was the natural application. $\endgroup$
    – Mr.Wizard
    Commented Jul 28, 2016 at 5:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

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