14
\$\begingroup\$

Create a Pascal's Triangle that is a nested list and contains zeros in the unused spots.

In the output array, the numbers of Pascal's Triangle are separated by zeroes and padded by zeroes on each side so that they are centered. For example, the bottom row (last sub-array) must have no zeroes on the left and the right; the second-last sub-array has one zero padding on each side, and so on.

Here is the output for input 5:

[[0,0,0,0,1,0,0,0,0],
[0,0,0,1,0,1,0,0,0],
[0,0,1,0,2,0,1,0,0],
[0,1,0,3,0,3,0,1,0],
[1,0,4,0,6,0,4,0,1]]

As usual, the solution with the fewest bytes wins.

\$\endgroup\$
4
  • 2
    \$\begingroup\$ Well, there are the extra zeros. \$\endgroup\$ Commented Feb 29, 2016 at 4:46
  • \$\begingroup\$ This program prints the one you want (Python 3):print("def pascal(n):\n #make the nested list\n a=[[0 for i in range(2*n+1)] for j in range(n+1)] #make the list\n a[0][n]=1 #add the initial 1\n for i in range(1,n+1):\n for j in range(2*n+1):\n a[i][j]=a[i-1][j-1]+a[i-1][(j+1)%(2*n+1)] #the main part\n return a") \$\endgroup\$ Commented Feb 29, 2016 at 4:53
  • 1
    \$\begingroup\$ @CatsAreFluffy The extra zeroes just replace the spaces in the previous iteration - this is functionally the exact same problem. \$\endgroup\$
    – ricdesi
    Commented Feb 29, 2016 at 14:42
  • 2
    \$\begingroup\$ Can I use the native array representation syntax for my language, or is the format non-negotiable? \$\endgroup\$
    – cat
    Commented Feb 29, 2016 at 15:46

15 Answers 15

5
\$\begingroup\$

Jelly, 13 bytes

Nr=0ṙ-,1S$³Ð¡

Try it online!

Explanation

Nr                 Get the range [-n -n+1 ... 0 ... n-1 n].
  =0                Logical NOT the entire range: [0 0 ... 1 ... 0 0].
         $³Ð¡       Repeat n times, and cumulate the results:
    ṙ-,1                Rotate by both -1 and 1
        S               Sum the results.
\$\endgroup\$
6
  • \$\begingroup\$ this seems to give no output \$\endgroup\$
    – Razetime
    Commented Dec 17, 2021 at 14:03
  • 1
    \$\begingroup\$ @Razetime I guess that -5R was [-5, -4, ... 5] in some super-old version of Jelly, but now it's the empty list. I'll fix it, but probably a modern Jelly answer could be way shorter. \$\endgroup\$
    – lynn
    Commented Dec 17, 2021 at 14:25
  • \$\begingroup\$ How do you learn to write jelly? I've been trying but Im struggling to do basic stuff since it works so much differently from "normal" languages (C, C#, python, etc). Normally I teach myself by googling stuff, but It seems like there is no help online beyond what's in the github repo \$\endgroup\$
    – Nigel
    Commented Dec 17, 2021 at 23:27
  • \$\begingroup\$ The logical not is really clever \$\endgroup\$
    – Nigel
    Commented Dec 17, 2021 at 23:28
  • \$\begingroup\$ You can join the jelly hypertraining chatroom for help with your programs: chat.stackexchange.com/rooms/57815/jelly-hypertraining Some people are also willing to give a beginner friendly tutorial \$\endgroup\$
    – Razetime
    Commented Dec 18, 2021 at 3:00
4
\$\begingroup\$

BQN, 20 17 bytes

-3 bytes thanks to/inspired by ovs

{(«+»)⍟𝕩0=1↓∾˜𝕩}↕

Anonymous function that takes an integer and returns a list of lists. Run it online!

\$\endgroup\$
2
  • \$\begingroup\$ Being able to use the Repeat operator with an Array argument is very neat! (not possible in APL) {(«+»)⍟𝕩¬×1↓𝕩∾𝕩}⟜↕ saves two bytes \$\endgroup\$
    – ovs
    Commented Dec 17, 2021 at 23:43
  • \$\begingroup\$ Ah, nice (and the isn't necessary, either). Still wish there were a good way to write the whole thing tacitly. \$\endgroup\$
    – DLosc
    Commented Dec 18, 2021 at 2:05
3
\$\begingroup\$

Mathematica, 70 68 bytes

NestList[ListConvolve[{1,0,1},#,2]&,Join[#,{1},#],#2]&[0~Table~#,#]&

Similar to the MATL solution.

\$\endgroup\$
3
\$\begingroup\$

Mathematica, 48 bytes

CellularAutomaton[{#+#3&@@#&,{},1},{{1},0},#-1]&

CellularAutomation is fantastic.

\$\endgroup\$
1
\$\begingroup\$

Haskell, 66 bytes

q n|d<-0<$[2..n]=scanl(\(s:t)_->zipWith(+)(0:s:t)$t++[0])(d++1:d)d

Usage example: q 4 -> [[0,0,0,1,0,0,0],[0,0,1,0,1,0,0],[0,1,0,2,0,1,0],[1,0,3,0,3,0,1]].

How it works:

d <- 0<$[2..n]                      -- bind d to a list of (length n)-1 zeros
scanl                               -- build a list
                         (d++1:d)   -- starting with  [d ++ 1 ++ d]
      \(s:t)_                    d  -- by combining the previous element with the
                                    -- elements of d, but ignoring them, i.e.
                                    -- build a list of (length d) by repeatedly
                                    -- modifying the start element by
          zipWith(+)                -- adding element-wise
                    (0:s:t)         -- the previous element prepended by 0  
                           t++[0]   -- and the tail of the previous element
                                    -- followed by a 0 
\$\endgroup\$
1
\$\begingroup\$

Javascript, 152 146 bytes

f=i=>[...Array(i)].map((x,j)=>(z=[...Array(i*2-1)].map((_,k)=>+!!~[i-j,i+j].indexOf(k+1)),y=j?z.map((_,k)=>_||(k&&(k+1 in y)?y[k-1]+y[k+1]:_)):z))

f=i=>[...Array(i)].map(
    (x,j)=>(
        z=[...Array(i*2-1)].map(
            (_,k)=>
                +!!~[i-j,i+j]
                    .indexOf(k+1)
        ),
        y=j?z.map(
            (_,k)=>_||
                (k&&(k+1 in y)?
                    y[k-1]+y[k+1]
                :_)
        ):z
    )
)

F=i=>JSON.stringify(f(+i)).replace(/],|^.|.(?=.$)/g,'$&\n')
I.oninput()
<input id=I onInput="O.innerHTML=F(I.value)" value=5><pre id=O>

\$\endgroup\$
1
\$\begingroup\$

Python 3, 172 158 133 bytes

def p(n):
 x=2*n+1;y=range
 a=[[0]*x]*n;a[0][n]=1
 for i in y(1,n+1):
  for j in y(x):a[i][j]=a[i-1][j-1]+a[i-1][(j+1)%(x)]
 return a

Keeps getting better

\$\endgroup\$
2
  • 1
    \$\begingroup\$ this isn't fully golfed yet, right? \$\endgroup\$
    – cat
    Commented Feb 29, 2016 at 15:41
  • \$\begingroup\$ Um, yeah. This (in a slightly less golfed form) is printed by a program I left a a comment on the question. \$\endgroup\$ Commented Feb 29, 2016 at 16:16
1
\$\begingroup\$

Seriously, 33 bytes

╩╜r`╣;lD0nkdZΣ`M╜rRZ`i0nkd@;)kΣ`M

Try it online

I'm relatively certain at least 7 or so of those bytes can be shaved off, so I'm going to wait to post an explanation until I'm done golfing this further.

\$\endgroup\$
1
\$\begingroup\$

MATL, 24 22 21 bytes

tEq:=Gq:"t5BX+8L)]N$v

EDIT (May 20, 2016): as of version 18.0.0 of the language, the above code needs a few changes to run. The link below includes those modifications

Try it online!

This uses a loop to push each new row onto the stack. A new row is computed from the previous row applying convolution with [1,0,1] and keeping only the desired size. After the loop, all rows are concatenated into a 2D array, which is displayed. 2D array are displayed in MATL as column-aligned numeric tables.

t           % implicit input n. Duplicate
Eq          % 2*n-1
:           % range [1,2,...,2*n-1]
=           % gives [0,0,...1,...0,0]. This is the first row
Gq:         % range [1,2,...,n-1]
"           % for each. Repeat n-1 times
  t         %   duplicate latest row. This duplicate will become the next row
  5B        %   push array [1,0,1] (5 converted to binary)
  X+        %   convolution
  8L        %   predefined literal [2,-1i]. Used for indexing
  )         %   apply that index: remove one element at each end
]           % end for each
N$v         % concatenate all rows into a 2D array. Implicitly display
\$\endgroup\$
1
\$\begingroup\$

PHP, 106 bytes

for(;$r++<$a=$argn;)for($c=-$a;++$c<$a;)$t[$r][$c]=$r>1|$c?$t[$r-1][$c-1]+$t[$r-1][$c+1]?:0:1;print_r($t);

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Brachylog, 27 26 bytes

~l{h1&jb}≜!{ẉ&h0&⟨↺z↻⟩+ᵐ↰}

Outputs N lists, separated by newlines. Try it online!

Explanation

This was harder than I expected. :P

~l{h1&jb}≜!{ẉ&h0&⟨↺z↻⟩+ᵐ↰}
~l                          Create a list whose length equals the input
  {     }                   Apply this predicate to it:
   h1                         The first element of the list is 1
     &                        and the list
      j                       concatenated to itself
       b                      with the first element removed
                              is the output of this predicate
                            Based on the order in which Brachylog tries possibilities,
                            the first list that satisfies these criteria will be
                            a list of N-1 zeros, a one, and N-1 more zeros
         ≜                  Instantiate that list
          !                 Cut: prevents backtracking past this point
           {             }  Apply this recursive predicate:
            ẉ                 Write the list with a newline
             &                and
              h0              The first element of the list must be 0
                &             and
                 ⟨↺           Take the list rotated left one place
                    ↻⟩        and the list rotated right one place
                   z          and zip them together
                      +ᵐ      Sum each of the resulting pairs
                              This generates the next row from the current
                              row, failing once the nonzero numbers reach the edge
                              of the list
                        ↰     Call the predicate again with this new list as input
\$\endgroup\$
0
\$\begingroup\$

Pari/GP, 44 bytes

n->[Vecrev((x+1/x)^i*x^n,2*n+1)|i<-[0..n--]]

Try it online!

\$\endgroup\$
0
\$\begingroup\$

Pascal, 235 B

A submission in Pascal may not be amiss. This function requires a processor supporting features of Extended Pascal as laid out by ISO standard 10206, in particular initial value specifiers (value) and schema data types.

type Z=integer;M(w,h:Z)=array[1..w,1..h]of Z
value[otherwise[otherwise 0]];p=^M;function f(n:Z)=r:p;var x,y:Z;begin
new(r,n*2-1,n);r^[n,1]:=1;for y:=2 to n do for x:=1 to r^.w do
r^[x,y]:=r^[x-1+ord(x<2),y-1]+r^[x+1-ord(x=r^.w),y-1]end

Antigolfed:

type
    { `Integer…` prefix for dictionary sorting with documentation tools. }
    integerPositive = 1‥maxInt;
    { The `value [otherwise [otherwise 0]]` ensures that
      all variables of this data type are initialized with zeros. }
    integerMatrix(
            width, height: integerPositive
        ) = array[1‥width, 1‥height] of integer
        value [otherwise [otherwise 0]];
    { Pointers can accommodate all discriminated types. }
    integerMatrixReference = ↑integerMatrix;

{ Functions cannot return variably‑sized data, therefore we need a pointer. }
function pascal(protected n: integerPositive) = result: integerMatrixReference;
    var
        { `For`‑loop counter variables have to be _proper_ variables.
          It is not possible to simply re‑use `n` or an `array` element. }
        x, y: integerPositive;
    begin
        new(result, n × 2 − 1, n);
        result↑[n, 1] ≔ 1;
        { Build lines from top to bottom. }
        for y ≔ 2 to n do
        begin
            { Fill lines from left to right. }
            for x ≔ 1 to result↑.width do
            begin
                { The member right above the current member is
                  the neutral element of addition, in other words zero. }
                result↑[x, y] ≔ result↑[pred(x) + ord(x < 2), pred(y)] +
                    result↑[succ(x) − ord(x ≥ result↑.width), pred(y)]
            end
        end
    end
\$\endgroup\$
0
\$\begingroup\$

05AB1E, 13 bytes

Lαû_IGÐÁsÀ+})

Port of @Lynn's Jelly answer.

Try it online.

If outputting each inner list on a separated newline is allowed, it could be 1 byte less instead:

Lαû_IF=DÁsÀ+

Try it online.

Explanation:

L          # Push a list in the range [1, (implicit) input]
 α         # Take the absolute difference of each with the input: [input-1,input-2,...,1,0]
  û        # Palindromize it
   _       # Check for each inner value whether it's equal to 0 (0s with 1 in the center)
    IG     # Loop the input-1 amount of times:
      Ð    #  Triplicate the current list
       Á   #  Pop the top, and rotate it once towards the right
      s    #  Swap so another copy is at the top
       À   #  Pop and rotate it once towards the left instead
        +  #  Add the values in the two rotates lists together
     })    # After the loop: wrap all lists on the stack into a list
           # (after which this matrix is output implicitly as result)

    IF     # Loop the input amount of times:
      =    #  Print the current list with trailing newline (without popping)
       D   #  Duplicate the list
           # (nothing is implicitly printed, since we've already printed explicitly prior)
\$\endgroup\$
0
\$\begingroup\$

MathGolf, 14 bytes

(_╤m┬\ô_‼╫╪m+]

Port of @Lynn's Jelly answer.

Try it online.

If outputting the inner lists concatted is allowed, the trailing ] could be omitted:
Try it online.

If outputting the result for \$n+1\$ instead of \$n\$ is allowed, the leading (_ can be omitted:
Try it online.

Explanation:

(          # Decrease the (implicit) input-integer by 1
 _         # Duplicate this input-1
  ╤        # Push a list in the range [-n-1,n-1]: [-n-1,-n,-n+1,...,-1,0,1,...,n-2,n-1]
   m       # Map over each inner integer:
    ┬      #  Check whether it equals 0 (1 if 0; 0 otherwise)
 \         # Swap so the duplicated input-1 is at the top
  ô        # Loop that many times, with 6 characters as inner code-block:
   _       #  Duplicate the current list
    ‼      #  Apply the next two builtins separately on the current list at the top of
           #  the stack:
     ╫     #   Rotate once towards the left
     ╪     #   Rotate once towards the right
      m+   #  Add the values at the same positions in the lists together
        ]  # After the loop: wrap all lists on the stack into a list
           # (after which the entire stack is output implicitly as result)
\$\endgroup\$

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