2
$\begingroup$

I want to create a variable list like this:

{0, 0, ..., 0, 0, 1, 1}

This list would grow list this, starting with no 0's, but then gaining more 0's to the left the larger you want it.

f[0] := {1, 1}

f[1] := {0, 1, 1}

f[2] := {0, 0, 1, 1}

f[3] := {0, 0, 0, 1, 1}

f[4] := {0, 0, 0, 0, 1, 1}

I know that I can use Table to create ten 0 by doing

Table[0, 10]
{0, 0, 0, 0, 0, 0, 0, 0, 0, 0}

but not an efficient way to have it so that the last two digits are 1.

$\endgroup$
4
  • $\begingroup$ SparseArray? PadRight/Left? $\endgroup$
    – Kuba
    Jul 11 '20 at 5:57
  • $\begingroup$ Not able to use SparseArray, but I just realised that I can use Flattern[]. $\endgroup$
    – Robjobbob
    Jul 11 '20 at 5:58
  • 6
    $\begingroup$ PadLeft and PadRight would be better than the solution you found. There’s also Join and Catenate which are used for this, rather than Flatten. $\endgroup$
    – C. E.
    Jul 11 '20 at 7:23
  • $\begingroup$ list[nzeros_] := PadLeft[{1, 1}, nzeros + 2] usage list[0], list[1], list[6], etc. $\endgroup$
    – flinty
    Jul 11 '20 at 13:19
7
$\begingroup$

A few additional alternatives:

ClearAll[ap, ur, ar, cr, ab, sa]

ap = ArrayPad[{1, 1}, {#, 0}] &;

ur = UnitStep[Range[# + 2] - # - 1/2] &;

ar = Reverse @ ArrayReshape[{1, 1}, # + 2] &;

cr = Clip[Range[# + 2], {#, #} + 1/2, {0, 1}] &;

ab = Array[a \[Function] Boole[a > #], # + 2] &;

sa = Normal @ SparseArray[{# + 1 | # + 2 -> 1}, # + 2] &;

Examples:

Through[{ap, ur, ar, cr, ab, sa} @ 0]
{{1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}, {1, 1}}
Through[{ap, ur, ar, cr, ab, sa} @ 3]
{{0, 0, 0, 1, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 1, 1}, {0, 0, 0, 1, 1}, 
{0, 0, 0, 1, 1}, {0, 0, 0, 1, 1}}
Through[{ap, ur, ar, cr, ab, sa}@5]
{{0, 0, 0, 0, 0, 1, 1}, {0, 0, 0, 0, 0, 1, 1}, {0, 0, 0, 0, 0, 1, 1},
{0, 0, 0, 0, 0, 1, 1}, {0, 0, 0, 0, 0, 1, 1}, {0, 0, 0, 0, 0, 1, 1}}
$\endgroup$
1
6
$\begingroup$

You are asking for the digits in the base 2 representation of the number 3, with some number, call it $n_0$, of leading zeros.

Clear[f]

f[n0_] := IntegerDigits[3, 2, n0 + 2]

f[0]    (* {1, 1} *)
f[1]    (* {0, 1, 1} *)
f[2]    (* {0, 0, 1, 1} *)
f[10]   (* {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1} *)
$\endgroup$
3
$\begingroup$

Using Join[] and Table[] seems to be the easiest way to do it.

fn[n_] := Join[Table[0, n],{1, 1}];

fn[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 1, 1}
$\endgroup$
2
  • $\begingroup$ alternatively: Flatten[{ConstantArray[0, n], {1,1} }] $\endgroup$
    – bill s
    Jul 11 '20 at 15:42
  • 4
    $\begingroup$ or Join[ConstantArray[0, n], {1,1}] $\endgroup$
    – user1066
    Jul 11 '20 at 17:07

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

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