22
\$\begingroup\$

Upside-Down Pyramid Addition is the process of taking a list of numbers and consecutively adding them together until you reach one number.

When given the numbers 2, 1, 1 the following process occurs:

 2   1   1
   3   2 
     5

This ends in the number 5.


YOUR TASK

Given the right side of an Upside-Down Pyramid (Ascending), write a program or function that will return the original list.

New Extra Challenge: Try doing this in less than O(n^2)

EXAMPLE

f([5, 2, 1]) => [2, 1, 1]
f([84,42,21,10,2]) => [4,7,3,8,2]

NOTE: The Upside-Down Pyramid will never be empty and will always consist of positive integers ONLY.

\$\endgroup\$
  • 6
    \$\begingroup\$ Welcome to PP&CG! This challenge is decent, though it could be improved. I'd recommend posting your challenges in the Sandbox first to improve the post before it's put on main. \$\endgroup\$ – Tau Apr 30 at 13:07
  • 13
    \$\begingroup\$ Free insight that I can't find a language it's shorter in: $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix} $$ \$\endgroup\$ – Lynn Apr 30 at 20:10
  • 4
    \$\begingroup\$ Just FYI, this is the same as the CodeWars kata. \$\endgroup\$ – ggorlen Apr 30 at 20:44
  • 6
    \$\begingroup\$ @ggorlen i know. I’m the one who made the kata :) \$\endgroup\$ – Whimpers Apr 30 at 22:34
  • 8
    \$\begingroup\$ Try doing this in less than O(n) surely it's impossible to allocate a n-sized array or change O(n) items in it faster than O(n) complexity? \$\endgroup\$ – someone May 1 at 3:45

23 Answers 23

17
\$\begingroup\$

JavaScript (ES6),  62 58 49  46 bytes

Saved 3 bytes thanks to @Oliver

Returns the list as a comma-separated string.

f=a=>+a||f(a.map(n=>a-(a=n),a=a.shift()))+[,a]

Try it online!

Commented

f = a =>              // f = recursive function taking the input list a[]
  +a                  // if a[] consists of a single positive integer:
                      //   stop recursion and return this integer
  ||                  // else:
    f(                //   do a recursive call to f:
      a.map(n =>      //     for each value n in a[]:
        a - (a = n),  //       yield the difference between the previous value and n
                      //       and update a to n
        a = a.shift() //       start by removing the first element and saving it in a
                      //       (because of the recursion, it's important here to reuse
                      //       a variable which is defined in the scope of f)
      )               //     end of map()
    )                 //   end of recursive call
    + [, a]           //   append the last entry from a[]
\$\endgroup\$
  • \$\begingroup\$ @Oliver, yes \$\endgroup\$ – Shaggy May 1 at 8:36
7
\$\begingroup\$

Haskell, 42 bytes

f[]=[]
f a=f(zipWith(-)a$tail a)++[last a]

Try it online!

\$\endgroup\$
6
\$\begingroup\$

TI-BASIC, 54 bytes

Ans→L₁:dim(L₁→dim(L₂:While 1-Ans:L₁(Ans→L₂(Ans:-ΔList(L₁→L₁:dim(Ans:End:L₁(Ans→L₂(Ans:L₂

Input is the list of the right side of the triangle in Ans, as is described in the challenge.
Output is the top row of said triangle.

Examples:

{5,2,1
         {5 2 1}
prgmCDGF19
         {2 1 1}
{84,42,21,10,2
 {84 42 21 10 2}
prgmCDGF19
     {4 7 3 8 2}

Explanation:
This solution abuses the fact that the triangle formed using the right side of the triangle as the start ends up being the change in each element.

In other words,

2 1 1
 3 2
  5

becomes:

5 2 1
 3 1
  2

Thus, the resulting list is the right side of this new triangle, which can be formed by setting the last element to the index of its parent list's length in the resulting list.

Ans→L₁          ;store the input list in L₁
dim(L₁→dim(L₂   ;set the length of L₂ to the length of L₁
While 1-Ans     ;while the L₁'s length is not 1
L₁(Ans→L₂(Ans   ;set the last element of L₁ to the corresponding index in L₂
-ΔList(L₁→L₁    ;get the change in each element, then negate
                ; (elements are in descending order so the change in each
                ;  element will be negative)
                ; and store the resulting list in L₁
dim(Ans         ;leave the length of L₁ in "Ans"
End
L₁(Ans→L₂(Ans   ;set the element again
                ; (needed for final step)
L₂              ;leave L₂ in "Ans"
                ;implicit print of "Ans"

Note: TI-BASIC is a tokenized language. Character count does not equal byte count.

\$\endgroup\$
6
\$\begingroup\$

Haskell, 22 bytes

foldl(flip$scanr(-))[]

Try it online!

\$\endgroup\$
4
\$\begingroup\$

Jelly, 6 bytes

ṚIƬZḢṚ

A monadic Link accepting a list of integers which yields a list of integers.

Try it online!

How?

Builds the whole triangle then extracts the required elements.

ṚIƬZḢṚ - Link: list of integers          e.g.  [84,42,21,10,2]
Ṛ      - reverse                               [2,10,21,42,84]
  Ƭ    - collect & apply until a fixed point:
 I     -   incremental differences            [[2,10,21,42,84],[8,11,21,42],[3,10,21],[7,11],[4],[]]
   Z   - transpose                            [[2,8,3,7,4],[10,11,10,11],[21,21,21],[42,42],[84]]
    Ḣ  - head                                  [2,8,3,7,4]
     Ṛ - reverse                               [4,7,3,8,2]
\$\endgroup\$
  • \$\begingroup\$ Had an almost identical solution but with Us instead of ! \$\endgroup\$ – Nick Kennedy Apr 30 at 14:16
  • \$\begingroup\$ IƬUZḢA would work with the given question too; I wonder if there is a byte save somewhere... \$\endgroup\$ – Jonathan Allan Apr 30 at 14:20
  • \$\begingroup\$ ạƝƬZṪ€ works too but is again a six. \$\endgroup\$ – Nick Kennedy Apr 30 at 15:01
  • \$\begingroup\$ Yep, I noticed that variant; I'm less hopeful now. \$\endgroup\$ – Jonathan Allan Apr 30 at 15:18
  • \$\begingroup\$ I just posted a 5-byter, but it's a bit different than your approach regarding the part after the pyramid construction. \$\endgroup\$ – Erik the Outgolfer Apr 30 at 19:01
4
\$\begingroup\$

MathGolf, 14 11 bytes

xÆ‼├│?;∟;]x

Try it online!

Explanation

x             reverse int/array/string
 Æ     ∟      do while true without popping using 5 operators
  ‼           apply next 2 operators to TOS
   ├          pop from left of list
    │         get differences of list
     ?        rot3
      ;       discard TOS (removes rest from ├ command)
              loop ends here
        ;     discard TOS (removes empty array from stack)
         ]    wrap stack in array
          x   reverse array
\$\endgroup\$
3
\$\begingroup\$

Python 2, 56 bytes

f=lambda a:a and f([l-r for l,r in zip(a,a[1:])])+a[-1:]

A recursive function accepting a list of positive integers which returns a list of non-negative integers.

Try it online!

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

Jelly, 5 bytes

_ƝƬa/

Try it online!

We can assume the whole pyramid is positive, so we can use a && operation instead of a "right" operation.

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

Pari/GP, 36 bytes

Based on @Lynn's comment:

Free insight that I can't find a language it's shorter in: $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

Pari/GP has a built-in for the Pascal matrix, and its inverse is exactly the matrix we need:

$$\begin{bmatrix} 1&0&0&0&0 \\ 1&1&0&0&0 \\ 1&2&1&0&0 \\ 1&3&3&1&0 \\ 1&4&6&4&1 \end{bmatrix}^{-1} = \begin{bmatrix} 1&0&0&0&0 \\ -1&1&0&0&0 \\ 1&-2&1&0&0 \\ -1&3&-3&1&0 \\ 1&-4&6&-4&1 \end{bmatrix}$$

a->r=Vecrev;r(r(a)/matpascal(#a-1)~)

Try it online!

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

R, 69 67 bytes

function(n,x=sum(n|1):1-1,`[`=outer)(x[x,choose]*(-1)^x[x,"+"])%*%n

Try it online!

Returns a column vector.

-2 bytes thanks to Kirill L.

Also based on Lynn's comment:

Free insight that I can't find a language it's shorter in: $$f([a,b,c,d,e]) = \begin{bmatrix} 1&-4&6&-4&1 \\ 0&1&-3&3&-1 \\ 0&0&1&-2&1 \\ 0&0&0&1&-1 \\ 0&0&0&0&1 \end{bmatrix} \cdot \begin{bmatrix}a\\b\\c\\d\\e\end{bmatrix}$$

It's longer than the other R answer, but it was an interesting approach to take and try to golf.

\$\endgroup\$
2
\$\begingroup\$

Javascript (ES6), 127 bytes

f=a=>{for(e=[a],a=[a[l=a.length-1]],i=0;i<l;i++){for(e.push(g=[]),j=-1;j<l;)g.push(e[i][j]-e[i][++j]);r.unshift(g[j])}return r}

Original code

function f(a){
  var e=[a];
  var r=[a[a.length-1]];
  for (var i=1;i<a.length;i++){
    var g=[];
    for (var j=0;j<a.length;j++){
      g.push(e[i-1][j-1]-e[i-1][j]);
    }
    e.push(g);
    r.unshift(g[j-1]);
  }
  return r;
}

Oh, I lost like... a lot... to the previous answer...

\$\endgroup\$
2
\$\begingroup\$

Wolfram Language (Mathematica), 57 bytes

(r=Reverse)[#&@@@Most@NestList[Differences,r@#,Tr[1^#]]]&

Try it online!

\$\endgroup\$
2
\$\begingroup\$

05AB1E, 12 11 bytes

R.¥.Γ¥}¨ζнR

Port of @JonathanAllan's Jelly answer, although I'm jelly about Jelly's more convenient builtins in this case. ;)
-1 byte thanks to @Emigna.

Try it online or verify all test cases.

Explanation:

R            # Reverse the (implicit) input-list
             #  i.e. [16,7,4,3] → [3,4,7,16]
 .¥          # Undelta it (with leading 0)
             #  → [0,3,7,14,30]
   .Γ }      # Continue until the result no longer changes, and collect all steps:
     ¥       #  Get the deltas / forward differences of the current list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4],[]]
       ¨     # Remove the trailing empty list
             #  → [[3,4,7,16],[1,3,9],[2,6],[4]]
        ζ    # Zip/transpose; swapping rows/column (with space as default filler)
             #  → [[3,1,2,4],[4,3,6," "],[7,9," "," "],[16," "," "," "]]
         н   # Only leave the first inner list
             #  → [3,1,2,4]
          R  # Revert it back
             #  → [4,2,1,3]
             # (after which it's output implicitly as result)
\$\endgroup\$
  • 2
    \$\begingroup\$ You can save a byte with R.¥.Γ¥}¨ by starting from the list whose delta is the input. \$\endgroup\$ – Emigna Apr 30 at 17:31
  • \$\begingroup\$ @Emigna Ah, undelta into a loop with deltas to save a byte on the prepend. :) Thanks! \$\endgroup\$ – Kevin Cruijssen Apr 30 at 18:13
2
\$\begingroup\$

R, 55 63 55 53 bytes

x=scan();for(i in sum(1|x):1){F[i]=x[i];x=-diff(x)};F

Try it online!

-2 bytes thanks to Giuseppe.

\$\endgroup\$
2
\$\begingroup\$

Perl 6, 37 bytes

{[R,]($_,{@(.[]Z-.skip)}...1)[*;*-1]}

Try it online!

Repeatedly reduces by elementwise subtraction, and then returns the last number of each list in reverse.

Explanation:

{                                  }  # Anonymous code block
      $_,               ...   # Create a sequence starting from the input
         {             }      # Where each element is
            .[]Z-.skip          # Each element minus the next element
          @(          )         # Arrayified
                           1  # Until the list has one element left
 [R,]                                # Reverse the sequence
     (                     )[*;   ]  # For every list
                               *-1   # Take the last element
\$\endgroup\$
1
\$\begingroup\$

Python 2, 78 bytes

lambda n,*a:R(lambda r,v:R(lambda x,w:x+[w-x[-1]],r,[v]),a,[n])[::-1]
R=reduce

Try it online!

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

C# (Visual C# Interactive Compiler), 164 bytes

a=>{int x=a.Length;var l=new int[x][];for(int i=0;i<x;i++){l[i]=new int[x];l[i][0]=a[i];for(int j=0;j<i;j++)l[i][j+1]=l[i-1][j]-l[i][j];}return l.Last().Reverse();}

Try it online!

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

Charcoal, 19 bytes

Fθ«PI§θ±¹↑UMθ⁻§θ⊖λκ

Try it online! Link is to verbose version of code. Explanation:

Fθ«

Loop once for each term in the original list.

PI§θ±¹↑

Print the last term in the list, but move the cursor to the beginning of the previous line, so that the terms are output in reverse order.

UMθ⁻§θ⊖λκ

Compute the deltas, inserting a dummy value at the beginning so that we can use an operation that doesn't change the length of the list.

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

APL+WIN, 34 or 28 bytes

v←⊂⌽⎕⋄1↓⌽↑¨⍎∊'v',(∊⍴¨v)⍴⊂',-2-/¨v'

Try it online! Courtesy of Dyalog Classic

Prompts for right side vector.

or implementing @Lynn's approach:

0⍕⌽(⌹⍉n∘.!n←0,⍳¯1+⍴n)+.×⌽n←⎕

Try it online!Courtesy of Dyalog Classic

Prompts for right side vector.

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

Attache, 29 bytes

{y.=Delta@-_If[_,$@y'_@-1,y]}

Try it online!

Simply iterates the Delta function until its empty. Much shorter than the very verbose PeriodicSteps solution...

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

C, 76 bytes

i=0;int*f(int*a,int n){for(;i<n;a[i++]=a[i]-a[i+1]);if(!n)return a;f(a,n-1);}  

input : (*a = pointer to array, n = last element's index of that array)
output : return int* = output

Explanation
going from right side to up, as the last elements are same in both input and output the loop inside function simply finds next higher numbers in the triangle gradually reaching to the top leaving the answer intact in the end.

ungolfed(from C++)

#include <iostream>
#define SIZE_F 5

int*recFind(int*a, int n) {
    int i = 0;
    while (i < n)
        a[i++] = a[i] - a[i+1];
    if (!n) return a;
        recFind(a, n - 1);
}
int main()
{
    int first[SIZE_F],*n;
    for (int i = 0; i < SIZE_F; i++)
        std::cin >> first[i];

    n = recFind(first, SIZE_F - 1);//size - 1
    for (int i = 0; i < SIZE_F; i++)
        std::cout << n[i];
}
\$\endgroup\$
1
\$\begingroup\$

Japt, 11 9 bytes

Nc¡=äa
yÌ

Try it

2 bytes saved thanks to Oliver.

12 11 bytes

_äa}hUÊN yÌ

Try it

1 byte saved thanks to Oliver.

\$\endgroup\$
  • 2
    \$\begingroup\$ 9 bytes and 10 bytes \$\endgroup\$ – Oliver May 1 at 3:58
  • \$\begingroup\$ @Oliver, not thinking to use y(f) is bad enough, but completely forgetting the newline is unforgivable! Will update shortly. Thanks :) \$\endgroup\$ – Shaggy May 1 at 8:38
1
\$\begingroup\$

Julia 0.6, 44 bytes

x->reverse([(j=x[end];x=-diff(x);j)for i=x])

Try it online!

Same iterative principle as my R answer.

Julia 0.6, 55 bytes

x->inv([binomial(i,j)for i=(l=length(x)-1:-1:0),j=l])*x

Try it online!

@Lynn's algorithm (inverse of Pascal matrix multiplied by input).

\$\endgroup\$

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.