# Create a list that always ends with two 1's but starts with a variable amount of 0's

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.

– Kuba
Jul 11 '20 at 5:57
• Not able to use SparseArray, but I just realised that I can use Flattern[]. Jul 11 '20 at 5:58
• 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. Jul 11 '20 at 7:23
• list[nzeros_] := PadLeft[{1, 1}, nzeros + 2] usage list[0], list[1], list[6], etc. Jul 11 '20 at 13:19

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}}

• f[n_] := SparseArray[{{-2}, {-1}} -> 1, n + 2] Jul 12 '20 at 8:29

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} *)


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}

• alternatively: Flatten[{ConstantArray[0, n], {1,1} }] Jul 11 '20 at 15:42
• or Join[ConstantArray[0, n], {1,1}] Jul 11 '20 at 17:07