21
\$\begingroup\$

Pascal's triangle is generated by starting with 1 and having each row formed from successive additions. Here, instead, we're going to form a triangle by alternating multiplication and addition.

We start row 1 with just a solitary 1. Thereafter, addition is done on the odd rows, and multiplication is done on the even rows (1-indexed). When performing the addition step, assume the spaces outside of the triangle are filled with 0s. When performing the multiplication step, assume that the outside is filled with 1s.

Here's the full triangle down to 7 rows. The * or + on the left shows what step was performed to generate that row.

1                1
2 *            1   1
3 +          1   2   1
4 *        1   2   2   1
5 +      1   3   4   3   1
6 *    1   3  12  12   3   1
7 +  1   4  15  24  15   4   1

Challenge

Given input n, output the nth row of this triangle.

Rules

  • You may choose to 0-index instead, but then please realize that the addition and multiplication rows must flip-flop, so that the exact same triangle is generated as above. Please state in your submission if you choose to do this.
  • The input and output can be assumed to fit in your language's native integer type.
  • The input and output can be given in any convenient format.
  • Either a full program or a function are acceptable. If a function, you can return the output rather than printing it.
  • If possible, please include a link to an online testing environment so other people can try out your code!
  • Standard loopholes are forbidden.
  • This is so all usual golfing rules apply, and the shortest code (in bytes) wins.

Examples

Showing two possible examples of output out of many: a list, or a space separated string.

4
[1, 2, 2, 1]

8
"1 4 60 360 360 60 4 1"
\$\endgroup\$
  • 2
    \$\begingroup\$ @totallyhuman No, the only thing to stdout should be the nth row. \$\endgroup\$ – AdmBorkBork Aug 9 '17 at 13:51

19 Answers 19

16
\$\begingroup\$

Pascal, 249 247 233 bytes

Well, this is Pascal's alternating triangle.

1 byte saved thanks to @Mr.Xcoder

function f(n,k:integer):integer;begin if((k<1)or(k>n)or(n=1))then f:=n mod 2 else if n mod 2=0then f:=f(n-1,k-1)*f(n-1,k)else f:=f(n-1,k-1)+f(n-1,k)end;
procedure g(n:integer);var k:integer;begin for k:=1to n do write(f(n,k),' ')end;

Try it online!

\$\endgroup\$
7
\$\begingroup\$

Python 2, 97 93 86 81 78 bytes

-4 bytes thanks to Rod. -10 bytes thanks to Halvard Hummel.

f=lambda n:n and[[i+j,i*j][n%2]for i,j in zip([n%2]+f(n-1),f(n-1)+[n%2])]or[1]

0-indexed.

Try it online!

\$\endgroup\$
5
\$\begingroup\$

Jelly, 17 12 bytes

µ×+LḂ$?Ḋ1;µ¡

This is a full program (or niladic link) that takes input from STDIN.

Try it online!

How it works

µ×+LḂ$?Ḋ1;µ¡  Main link. No arguments. Implicit argument: 0

          µ¡  Start a monadic chain and apply the ntimes quick to the previous one.
              This reads an integer n from STDIN and executes the previous chain n
              times, with initial argument 0, returning the last result.
µ             Start a monadic chain. Argument: A (array or 0)
       Ḋ          Dequeue; yield A without its first element.
   LḂ$?           If the length of A is odd:
 ×                    Multiply A and dequeued A.
                  Else:
  +                   Add A and dequeued A.
        1;        Prepend a 1 to the result.
\$\endgroup\$
5
\$\begingroup\$

Python 2, 96 89 87 bytes

s=a=[1]
for i in range(1,input()):a=s+[[k+l,k*l][i%2]for k,l in zip(a[1:],a)]+s
print a

Try it online!

\$\endgroup\$
  • 1
    \$\begingroup\$ Even shorter as a recursive function \$\endgroup\$ – ovs Aug 9 '17 at 14:23
  • \$\begingroup\$ @totallyhuman Thanks.. I rolled it back... \$\endgroup\$ – officialaimm Aug 9 '17 at 14:51
  • 1
    \$\begingroup\$ Suddenly exec method is leading :D \$\endgroup\$ – Dead Possum Aug 9 '17 at 14:54
  • 1
    \$\begingroup\$ 87 bytes, declaring [1]. \$\endgroup\$ – Mr. Xcoder Aug 9 '17 at 15:22
3
\$\begingroup\$

CJam, 25 bytes

{1a\{2%!_2$+\{.*}{.+}?}/}

0-indexed.

Try it online!

Explanation

This is an anonymous block that takes the number from the stack and leaves the result on the stack.

1a                        Push [1].
  \                       Bring the number to the top.
   {                 }/   For reach number 0 .. arg-1, do:
    2%!                    Push 0 if even, 1 if odd.
       _                   Copy that.
        2$+                Copy the list so far and prepend the 0 or 1 to it.
           \               Bring the 0 or 1 back to the top.
            {.*}{.+}?      If 1, element-wise multiplication. If 0, element-wise addition.
\$\endgroup\$
  • \$\begingroup\$ Wait 2%! should push 1 if even and 0 if odd, no? \$\endgroup\$ – Esolanging Fruit Feb 15 '18 at 1:58
3
\$\begingroup\$

Mathematica, 92 bytes

(s={i=1};While[i<#,s=Flatten@{1,{Tr/@#,Times@@@#}[[i~Mod~2+1]]&@Partition[s,2,1],1};i++];s)&

Try it online! (in order to work on mathics "Tr" is replaced with "Total")

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

Haskell, 76 72 bytes

0-indexed solution:

(p!!)
p=[1]:[zipWith o(e:l)l++[1]|(l,(o,e))<-zip p$cycle[((*),1),((+),0)]]

Try it online!

Explanation

p recursively defines the alternating triangle, the base case/first element of it is [1]

p=[1]:[                                                            ]

It then builds the triangle by taking the previous line (l). To know what to do with it we need to keep track of the correct operator (o) and the corresponding neutral element (e):

                           |(l,(o,e))<-zip p$cycle[((*),1),((+),0)]

From this build the new line by duplicating the line and for one copy we prepend the neutral element, zip them with the operator and append a 1:

       zipWith o(e:l)l++[1]
\$\endgroup\$
3
\$\begingroup\$

R, 108 98 bytes

-10 bytes by replacing the actual multiply sign with a plus sign. Please forgive me.

f=function(n){if(n<3)return(rep(1,n))else{v=f(n-1)};if(n%%2)`*`=`+`;return(c(1,v[3:n-2]*v[-1],1))}

Try it online!

Quite pleased with the general method (first time I've aliased a primitive) but I'm sure there's golfing to be done on it yet, especially with the awkward handling of cases where n<3 which leads to a lot of boilerplate.

\$\endgroup\$
  • \$\begingroup\$ 85 bytes. I really love your solution with `*`=`+`! quite clever. The rest of my improvements are just standard golfing techniques, which I would be happy to explain at your request :) \$\endgroup\$ – Giuseppe Sep 1 '17 at 18:47
  • \$\begingroup\$ 80 bytes. I took inspiration from your note about handling cases where n<3 \$\endgroup\$ – Giuseppe Sep 1 '17 at 18:56
2
\$\begingroup\$

Husk, 17 16 bytes

!G₅;1¢e*+
:1Sż⁰t

Try it online!

A 1-indexed solution.

Explanation

The first line is the main function, which calls the helper function on the second line. The helper function is usually called with , but in this case I'm using the overflowing labels feature of Husk: if you refer to a line N in a program with M < N lines, you get line N mod M with modifier function M / N applied to it. The second modifier function is flip, so I'm using to flip the arguments of the helper function with no additional byte cost.

Here is the helper function.

:1Sż⁰t  Takes a function f and a list x.
   ż    Zip preserving elements of longer list
    ⁰   using function f
  S  t  x and its tail,
:1      then prepend 1.

Here is the main function.

!G₅;1¢e*+  Takes a number n.
      e*+  2-element list of the functions * and +
     ¢     repeated infinitely.
 G         Left scan this list
  ₅        using the flipped helper function
   ;1      with initial value [1].
!          Get n'th element.
\$\endgroup\$
2
\$\begingroup\$

C# (.NET Core), 143 134 128 bytes

-4 bytes thanks to Phaeze
-5 bytes thanks to Zac Faragher
-6 bytes thanks to Kevin Cruijssen

n=>{int[]b={1},c;for(int i=0,j;++i<n;b=c)for(c=new int[i+1],c[0]=c[i]=1,j=0;++j<i;)c[j]=i%2<1?b[j-1]+b[j]:b[j-1]*b[j];return b;}

Try it online!

Explanation:

n =>
{
    int[] b = { 1 }, c;               // Create first layer
    for(int i = 0, j; ++i < n; b = c) // Iterate for every layer, replace last layer with a new one
        for(c = new int[i+1],         // Create new layer
            c[0] = c[i] = 1,          // First and last elements are always 1
            j = 0;
            ++j < i; )                // Replace every element (besides 1st and last)...
                c[j] = i % 2 == 0 ?
                    b[j - 1] + b[j] : // ... with addition...
                    b[j - 1] * b[j];  // ... or multiplication of two from previous layers
    return b;                         // Return latest layer
};
\$\endgroup\$
  • \$\begingroup\$ You should be able to change your b array initialization to var b=new[]{1}; and the compiler will determine the array type for you. \$\endgroup\$ – Phaeze Aug 9 '17 at 23:08
  • 1
    \$\begingroup\$ Another way to construct the first layer is int[]b={1}; - 11 bytes vs 20 as is or 16 as in @Phaeze 's suggestion \$\endgroup\$ – Zac Faragher Aug 10 '17 at 1:17
  • 1
    \$\begingroup\$ @ZacFaragher and Phaeze thank you! \$\endgroup\$ – Grzegorz Puławski Aug 10 '17 at 8:46
  • 1
    \$\begingroup\$ I know it's been quite a while, but you can golf 6 more bytes: n=>{int[]b={1},c;for(int i=0,j;++i<n;b=c)for(c=new int[i+1],c[0]=c[i]=1,j=0;++j<i;)c[j]=i%2<1?b[j-1]+b[j]:b[j-1]*b[j];return b;}. I've combined c like thisint[]b={1},c;; shortened i%2==0 to i%2<1; And removed the brackets of the loop by putting everything inside. \$\endgroup\$ – Kevin Cruijssen Feb 14 '18 at 8:31
  • \$\begingroup\$ Great! Thanks @KevinCruijssen \$\endgroup\$ – Grzegorz Puławski Feb 14 '18 at 13:21
1
\$\begingroup\$

Python 2, 83 bytes

Give some love to exec
0-indexed

l=[1];exec"l[1:]=[[a+b,a*b][len(l)%2]for a,b in zip(l,l[1:])]+[1];"*input()
print l

Try it online!

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

Pyth, 22 bytes

Saved tons of byte thanks to @FryAmTheEggman! The initial solution is below.

u++1@,+VGtG*VGtGlG1Q[1

Full Test Suite (0-indexed).

Pyth, 40 38 36 35 bytes

This feels waaaaaaaay too reasonably long. Suggestions are welcome.

K]1VStQ=K++]1m@,sd*hded%N2C,KtK]1;K

Test Suite or Try it online!

\$\endgroup\$
  • \$\begingroup\$ Using reduce seems to be much shorter. I'm not convinced this is optimal either, I think sub 20 is manageable? \$\endgroup\$ – FryAmTheEggman Aug 9 '17 at 17:18
  • \$\begingroup\$ @FryAmTheEggman See my revision history. I said I was trying to find a workaround with reduce u (but couldn't figure it out). Thanks! \$\endgroup\$ – Mr. Xcoder Aug 9 '17 at 17:18
  • \$\begingroup\$ If Pyth would have a prepend-append built-in... \$\endgroup\$ – Mr. Xcoder Aug 9 '17 at 17:36
1
\$\begingroup\$

J, 32 bytes

[:(1,]{::(}.@,-.)(*;+)[)~/2|]-i.

Try it online!

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

Perl 5, 111 + 2 (-na) = 113 bytes

sub t{($r,$c)=@_;!--$r||!$c||$c>=$r?1:eval"t($r,$c)".($r%2?"*":"+")."t($r,$c-1)"}say map{t($F[0],$_).$"}0..$_-1

Try it online!

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

Mathematica, 70 bytes

Fold[#2@@@Partition[#,2,1,{-1,1},{}]&,{1},PadRight[{},#,{1##&,Plus}]]&

Try it at the Wolfram sandbox! It doesn't work in Mathics, unfortunately. It's 0-indexed.

Explanation: Partition[#,2,1,{-1,1},{}] takes a list and returns all the two-element sublists, plus 1-element lists for the start and end — e.g., {1,2,3,4} becomes {{1}, {1,2}, {2,3}, {3,4}, {4}}. PadRight[{},#,{1##&,Plus}] makes an alternating list of 1##& (effectively Times) and Plus, whose length is the input number. Then Fold repeatedly applies the partition function with the Pluses and Timeses applied to it, to make the rows of the triangle.

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

Ruby, 83 82 bytes

->n{a=[1];p=0;n.times{a=[p=1-p,*a,p].each_cons(2).map{|x|x.reduce([:+,:*][p])}};a}

Try it online!

This is 0-indexed.

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

Racket, 116 bytes

(define(t n[i 1][r'(1)])(if(= n 1)r(t(- n 1)(- 1 i)(cons 1(append(map(if(> i 0)* +)(cdr r)(reverse(cdr r)))'(1))))))

Try it online!

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

TI-Basic (TI-84 Plus CE), 100 bytes

Prompt X
{1→M
For(A,2,X
LM→L
A→dim(M
For(B,2,A–1
If A/2=int(A/2
Then
LL(B–1)LL(B→LM(B
Else
LL(B–1)+LL(B→LM(B
End
End
1→LM(dim(LM
End
LM

1-indexed, prompts user for input and prints a list containing the nth row of Pascal's Alternating Triangle.

While looping: LM is the current row, and LL is the previous row.

TI-Basic is a tokenized language. All tokens used here are one-byte tokens.

I think I can golf this further by modifying M in-place from the end.

Explanation:

Prompt X            # 3 bytes; get user input, store in X
{1→M                # 5 bytes, store the first row into LM
For(A,2,X           # 7 bytes, Loop X-1 times, with A as the counter, starting at 2
LM→L                # 5 bytes, copy list M into list L
A→dim(M             # 5 bytes, extend M by one
For(B,2,A–1         # 9 bytes, for each index B that isn't the first or last...
If A/2=int(A/2      # 10 bytes,    if A is even...
Then                # 2 bytes,     then...
LL(B–1)LL(B→LM(B     # 17 bytes,        the Bth item in this row is the Bth times the (B-1)th of the previous row
Else                # 2 bytes,     else...
LL(B–1)+LL(B→LM(B    # 18 bytes,        the Bth item in this row is the Bth plus the (B-1)th of the previous row
End                 # 2 bytes,     endif
End                 # 2 bytes,  endfor
1→LM(dim(LM         # 9 bytes, the last item is always 1
End                 # 2 bytes, endfor
LM                  # 2 bytes, Implicitly print the final row

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

JavaScript (ES6), 71 69 66 bytes

f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1]

Try it online!

0-indexed.
-3 bytes by @Arnauld

f=n=>n?(p=f(n-1),[...p.map((v,i)=>i--?n%2?v*p[i]:v+p[i]:1),1]):[1]

for (var i = 0; i < 10; ++i) {
  console.log(JSON.stringify(f(i)));
}

\$\endgroup\$
  • 1
    \$\begingroup\$ Using a ternary should save 3 bytes: i--?n%2?v*p[i]:v+p[i] \$\endgroup\$ – Arnauld Aug 10 '17 at 14:10

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.