Pascal's Alternating Triangle

21

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"

AdmBorkBork

Posted 2017-08-09T13:40:53.167

Reputation: 41 581

2@totallyhuman No, the only thing to stdout should be the nth row. – AdmBorkBork – 2017-08-09T13:51:42.217

Answers

16

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!

Uriel

Posted 2017-08-09T13:40:53.167

Reputation: 11 708

248 bytes – Mr. Xcoder – 2017-08-09T14:15:06.367

7

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!

totallyhuman

Posted 2017-08-09T13:40:53.167

Reputation: 15 378

1

Good job, I had a (much) longer approach. Though I didn't have time to golf it yet.

– Mr. Xcoder – 2017-08-09T14:07:41.830

1I guess that map([int.__add__ ,int.__mul__][i%2],[i%2]+a,a+[i%2]) should work (didn't tested) – Rod – 2017-08-09T14:10:13.653

It don't have a zip, look closer – Rod – 2017-08-09T14:11:19.473

Rod is right, 94 bytes. – Mr. Xcoder – 2017-08-09T14:12:13.697

83 bytes – Halvard Hummel – 2017-08-09T14:13:30.997

I think I made an error – Halvard Hummel – 2017-08-09T14:14:51.560

@HalvardHummel That fails for 5 and 6. – Mr. Xcoder – 2017-08-09T14:16:11.627

1This should be correct – Halvard Hummel – 2017-08-09T14:25:31.657

You are allowed to put the "f=" in the header – Halvard Hummel – 2017-08-09T14:30:11.253

1No, this is recursive. You must include the name. – Mr. Xcoder – 2017-08-09T14:30:38.543

Ahh, okay. Learn something new every day – Halvard Hummel – 2017-08-09T14:31:07.707

1The rules allow 0 indexing – Halvard Hummel – 2017-08-09T15:38:04.567

5

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!

officialaimm

Posted 2017-08-09T13:40:53.167

Reputation: 2 739

1Even shorter as a recursive function – ovs – 2017-08-09T14:23:59.790

@totallyhuman Thanks.. I rolled it back... – officialaimm – 2017-08-09T14:51:02.170

1Suddenly exec method is leading :D – Dead Possum – 2017-08-09T14:54:44.940

187 bytes, declaring [1]. – Mr. Xcoder – 2017-08-09T15:22:05.880

5

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.

Dennis

Posted 2017-08-09T13:40:53.167

Reputation: 196 637

3

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.

Business Cat

Posted 2017-08-09T13:40:53.167

Reputation: 8 927

Wait 2%! should push 1 if even and 0 if odd, no? – Esolanging Fruit – 2018-02-15T01:58:02.890

3

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]

ბიმო

Posted 2017-08-09T13:40:53.167

Reputation: 15 345

3

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")

J42161217

Posted 2017-08-09T13:40:53.167

Reputation: 15 931

3

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.

CriminallyVulgar

Posted 2017-08-09T13:40:53.167

Reputation: 501

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 :) – Giuseppe – 2017-09-01T18:47:19.737

80 bytes. I took inspiration from your note about handling cases where n<3 – Giuseppe – 2017-09-01T18:56:11.130

2

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.

Zgarb

Posted 2017-08-09T13:40:53.167

Reputation: 39 083

1

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

Grzegorz Puławski

Posted 2017-08-09T13:40:53.167

Reputation: 781

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. – None – 2017-08-09T23:08:29.410

1Another way to construct the first layer is int[]b={1}; - 11 bytes vs 20 as is or 16 as in @Phaeze 's suggestion – Zac Faragher – 2017-08-10T01:17:09.247

1@ZacFaragher and Phaeze thank you! – Grzegorz Puławski – 2017-08-10T08:46:43.180

1

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.

– Kevin Cruijssen – 2018-02-14T08:31:28.223

Great! Thanks @KevinCruijssen – Grzegorz Puławski – 2018-02-14T13:21:33.050

1

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!

Dead Possum

Posted 2017-08-09T13:40:53.167

Reputation: 3 256

1

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!

Mr. Xcoder

Posted 2017-08-09T13:40:53.167

Reputation: 39 774

Using reduce seems to be much shorter. I'm not convinced this is optimal either, I think sub 20 is manageable?

– FryAmTheEggman – 2017-08-09T17:18:08.607

@FryAmTheEggman See my revision history. I said I was trying to find a workaround with reduce u (but couldn't figure it out). Thanks! – Mr. Xcoder – 2017-08-09T17:18:57.860

If Pyth would have a prepend-append built-in... – Mr. Xcoder – 2017-08-09T17:36:31.830

1

J, 32 bytes

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

Try it online!

miles

Posted 2017-08-09T13:40:53.167

Reputation: 15 654

1

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!

Xcali

Posted 2017-08-09T13:40:53.167

Reputation: 7 671

1

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.

Not a tree

Posted 2017-08-09T13:40:53.167

Reputation: 3 106

0

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.

Nnnes

Posted 2017-08-09T13:40:53.167

Reputation: 395

0

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!

Business Cat

Posted 2017-08-09T13:40:53.167

Reputation: 8 927

0

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

pizzapants184

Posted 2017-08-09T13:40:53.167

Reputation: 3 174

0

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

Birjolaxew

Posted 2017-08-09T13:40:53.167

Reputation: 323

1Using a ternary should save 3 bytes: i--?n%2?v*p[i]:v+p[i] – Arnauld – 2017-08-10T14:10:53.610