[Question]
  [
**Closed.** This question is [off-topic](/help/closed-questions). It is not currently accepting answers.
 
 
---
 Questions without an **objective primary winning criterion** are off-topic, as they make it impossible to indisputably decide which entry should win.
Closed 3 years ago.
[Improve this question](/posts/184951/edit) 
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.
  
[Answer]
# 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!](https://tio.run/##XYuxDoIwFEV3v4LxvXApUmtkKT9CGF6QKgZbYokT/17r4OIdzzn3IW@J42tet8qH65SSs2K7UvbdkainrORtJxWJ9QyxouJ9dhsxc9lDhjQGH8MyqSXcyFF/hkYzMBe/1XWRCZrDX9gaGA2dzRH6e8ihwQUntNDpAw "JavaScript (Node.js) – 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[]
```
[Answer]
# [Haskell](https://www.haskell.org/), 22 bytes
```
foldl(flip$scanr(-))[]
```
[Try it online!](https://tio.run/##VcixDkAwEADQ3VfcYKjkJNqQWHwJHZpyNE41re93Zm98hyvnxiw0LUI3r6yIQ6qLdzGrtmlmK5cLESZY7wog5RAfqIFgHtCgtv8be@wNGo26Q2Pl9cRuL9L6lD4 "Haskell – Try It Online")
[Answer]
## Haskell, 42 bytes
```
f[]=[]
f a=f(zipWith(-)a$tail a)++[last a]
```
[Try it online!](https://tio.run/##Vcg7CoAwEAXA3lO8wkJxBRMUbHIOi7DFggYX4wdN5eVj7ZSzyrMtMeYcPDvPRYC4UL16TZrWqq2lTKIRUjeNj/IkCOdd9IDDfBbAdeuRUCLAD2TJ8P/GnnpL1pDpyHL@AA "Haskell – Try It Online")
[Answer]
# 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.
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 6 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
ṚIƬZḢṚ
```
A monadic Link accepting a list of integers which yields a list of integers.
**[Try it online!](https://tio.run/##y0rNyan8///hzlmex9ZEPdyxCMj6//9/tIWxjoKRuY6CpY4CkDSLBQA "Jelly – 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]
```
[Answer]
# [MathGolf](https://github.com/maxbergmark/mathgolf), ~~14~~ 11 bytes
```
xÆ‼├│?;∟;]x
```
[Try it online!](https://tio.run/##ATgAx/9tYXRoZ29sZv//eMOG4oC84pSc4pSCPzviiJ87XXj//1s1IDIgMV0KWzg0IDQyIDIxIDEwIDJd/w "MathGolf – 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
```
[Answer]
# [Python 2](https://docs.python.org/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!](https://tio.run/##K6gsycjPM/r/P802JzE3KSVRIdEKiPNSFNI0onN0ixTS8osUcnSKFDLzFKoyCzQSdRKjDa1iNWM1tROjdYGs/wVFmXklINUWJjomRjpGhjqGBjpGsZr/AQ "Python 2 – Try It Online")**
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 5 bytes
```
_ƝƬa/
```
[Try it online!](https://tio.run/##y0rNyan8/z/@2NxjaxL1/x9uPzrp4c4Z//9HW5joKJgY6SgYGeooGBoA6VgA "Jelly – Try It Online")
We can assume the whole pyramid is positive, so we can use a && operation instead of a "right" operation.
[Answer]
# [Pari/GP](http://pari.math.u-bordeaux.fr/), 36 bytes
Based on [@Lynn](https://codegolf.stackexchange.com/users/3852/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!](https://tio.run/##K0gsytRNL/ifpmD7P1HXrsg2LDW5KLXMukijSCNRUz83saQgsTg5MUdDOVHXULNO839iQUFOpUaigq6dQkFRZl4JkKkE4igppAE1aOooREeb6hjpGMYCWRYmOiZGOkaGOoYGOkaxsZr/AQ "Pari/GP – Try It Online")
[Answer]
# [R](https://www.r-project.org/), ~~69~~ 67 bytes
```
function(n,x=sum(n|1):1-1,`[`=outer)(x[x,choose]*(-1)^x[x,"+"])%*%n
```
[Try it online!](https://tio.run/##FchBCoMwEAXQvacogjCjP@AEhVLqSUQRgqFddALGQBbePcXd4x3FP96m@KTu/AYlRZ5i@pFewi8xgm3eppDO/WDKc4b7hBD3pSUjvN5Rd/XCTdto8eRohIUwV7efAwYLK5Aelrn8AQ "R – Try It Online")
Returns a column vector.
-2 bytes thanks to [Kirill L.](https://codegolf.stackexchange.com/users/78274/kirill-l)
Also based on [Lynn](https://codegolf.stackexchange.com/users/3852/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.
[Answer]
# 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...
[Answer]
# [Wolfram Language (Mathematica)](https://www.wolfram.com/wolframscript/), 57 bytes
```
(r=Reverse)[#&@@@Most@NestList[Differences,r@#,Tr[1^#]]]&
```
[Try it online!](https://tio.run/##y00syUjNTSzJTE78n277X6PINii1LLWoOFUzWlnNwcHBN7@4xMEvtbjEJ7O4JNolMy0ttSg1Lzm1WKfIQVknpCjaME45NjZW7X9AUWZeiYJDenS1qY6RjmFtLBdYJDpWgQshZWGiY2KkY2SoY2igY1Qb@/8/AA "Wolfram Language (Mathematica) – Try It Online")
[Answer]
# [05AB1E](https://github.com/Adriandmen/05AB1E/wiki/Commands), ~~12~~ 11 [bytes](https://github.com/Adriandmen/05AB1E/wiki/Codepage)
```
R.¥.Γ¥}¨ζнR
```
Port of [*@JonathanAllan*'s Jelly answer](https://codegolf.stackexchange.com/a/184958/52210), although I'm *jelly* about Jelly's more convenient builtins in this case. ;)  
-1 byte thanks to *@Emigna*.
[Try it online](https://tio.run/##ASoA1f9vc2FiaWX//1IuwqUuzpPCpX3CqM620L1S//9bODQsNDIsMjEsMTAsMl0) or [verify all test cases](https://tio.run/##yy9OTMpM/V9Waa@k8KhtkoKSfeX/IL1DS/XOTT60tPbQinPbLuwN@q/zPzraVMdIxzBWRyHawkTHxEjHyFDH0EDHCCRgaKZjrmOiYxwbCwA).
**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)
```
[Answer]
# [R](https://www.r-project.org/), ~~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!](https://tio.run/##K/r/v8K2ODkxT0PTOi2/SCNTITNPobg0V8OwpkLTylCz2i06M9a2AkhYV9jqpmSmpWlUaNZau/23MFEwMVIwMlQwNFAw@g8A "R – Try It Online")
-2 bytes thanks to Giuseppe.
[Answer]
# [Perl 6](https://github.com/nxadm/rakudo-pkg), 37 bytes
```
{[R,]($_,{@(.[]Z-.skip)}...1)[*;*-1]}
```
[Try it online!](https://tio.run/##K0gtyjH7n1upoJamYPu/OjpIJ1ZDJV6n2kFDLzo2SlevODuzQLNWT0/PUDNay1pL1zC29n9afpGCRk5mXmqxpkI1l4JCcWKlgp5rmKOPnloaV@1/DVMdBSMdBUNNAA "Perl 6 – 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
```
[Answer]
# [Python 2](https://docs.python.org/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!](https://tio.run/##K6gsycjPM/qfZhvzPycxNyklUSFPRyvRKkgDyivSKUNwKnTKrSq0o8t1K6J1DWNjdYp0ostiNXUSdaLzYjWjrayAglxBtkWpKaXJqf8LijLzShTSNEx1jHQMNf8DAA "Python 2 – Try It Online")
[Answer]
## [C# (Visual C# Interactive Compiler)](https://www.mono-project.com/docs/about-mono/releases/5.0.0/#csc), 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!](https://tio.run/##lY5PS8QwEMXvforBU0L/0C4rCGl6EQWlJy8eSg6xTNcpNYUkXQtLP3uduiBehYE37/F@w3Qh6wJtT7PrKnKxNenzo5s/0dv3EfekrqHXm9X1hQ0s2uYNulP8UGfrYdQOv2DnFtMa1U9e7C3ShaJqUZQk8jK2ZP7U1O7bwmjL@ksMTAwVqYGJn8KQlEbzlpW8m@yaGbV6jLN3MOaNDVHI/BXP6AMKqdZN3TxMLkwj5m@eIjbkUIToyZ3yl4mcuE2Bpxf8TGvgAncpHFIoYZVS/pe9P6ZwZPpQ8oWCFa5ntm8)
[Answer]
# [Charcoal](https://github.com/somebody1234/Charcoal), 19 bytes
```
Ｆθ«ＰＩ§θ±¹↑ＵＭθ⁻§θ⊖λκ
```
[Try it online!](https://tio.run/##S85ILErOT8z5/z8tv0hBo1BToZqL07c0pySzoCgzr0TDObG4RMOxxDMvJbVCo1BHwS81PbEkVcNQEwisgSrzy1I1rEILwOzEAuf83NzEvBSQQt/MvNJiZJ0uqclFqbmpeSWpKRo5mpo6CtkgE2r//4@ONtVRMNJRMIyN/a9blgMA "Charcoal – Try It Online") Link is to verbose version of code. Explanation:
```
Ｆθ«
```
Loop once for each term in the original list.
```
ＰＩ§θ±¹↑
```
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.
```
ＵＭθ⁻§θ⊖λκ
```
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.
[Answer]
# APL+WIN, 34 or 28 bytes
```
v←⊂⌽⎕⋄1↓⌽↑¨⍎∊'v',(∊⍴¨v)⍴⊂',-2-/¨v'
```
[Try it online! Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/6XAZmPupoe9ewFSjzqbjF81DYZxGmbeGjFo96@Rx1d6mXqOhpA@lHvlkMryjSBFFC9uo6uka4@kK/@H2jM/zQuCxMFEyMFI0MFQwMFIwA "APL (Dyalog Classic) – Try It Online")
Prompts for right side vector.
or implementing @Lynn's approach:
```
0⍕⌽(⌹⍉n∘.!n←0,⍳¯1+⍴n)+.×⌽n←⎕
```
[Try it online!Courtesy of Dyalog Classic](https://tio.run/##SyzI0U2pTMzJT9dNzkksLs5M/v@ob6qvz6O2CcZcjzra0/4bPOqd@qhnr8ajnp2PejvzHnXM0FPMA0ob6Dzq3XxovaH2o94teZraeoenA1WBJID6/wN1/k/jsjBRMDFSMDJUMDRQMAIA "APL (Dyalog Classic) – Try It Online")
Prompts for right side vector.
[Answer]
# [Attache](https://github.com/ConorOBrien-Foxx/Attache), 29 bytes
```
{y.=Delta@-_If[_,$@y'_@-1,y]}
```
[Try it online!](https://tio.run/##SywpSUzOSP2fpmBl@7@6Us/WJTWnJNFBN94zLTpeR8WhUj3eQddQpzK29r9fampKcbRKQUFyeixXQFFmXklIanGJc2JxanF0mo5CtKW6qY6CqbqRuqGOgoWJuomRupGhuqGBulFs7H8A "Attache – Try It Online")
Simply iterates the `Delta` function until its empty. Much shorter than the very verbose `PeriodicSteps` solution...
[Answer]
# 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];
}
```
[Answer]
# [Japt](https://github.com/ETHproductions/japt), ~~11~~ 9 bytes
```
Nc¡=äa
yÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=TmOhPeRhCnnM&input=Wzg0LDQyLDIxLDEwLDJd)
2 bytes saved thanks to Oliver.
## ~~12~~ 11 bytes
```
_äa}hUÊN yÌ
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=X%2bRhfWhVyk4gecw&input=Wzg0LDQyLDIxLDEwLDJd)
1 byte saved thanks to Oliver.
[Answer]
# [Julia 0.6](http://julialang.org/), 44 bytes
```
x->reverse([(j=x[end];x=-diff(x);j)for i=x])
```
[Try it online!](https://tio.run/##Xck9CoAwDEDh3VM4JoNgi4oQ6kVKB8EGWqRK/SG3r47i@L4XrzXMQ2FTpJmyv30@PFiIRqxPiyMxzRKYQZAi8pbrYMRh2XNI55qAwSqHWH26J01/GzvqNGlFqiX9vvIA "Julia 0.6 – Try It Online")
Same iterative principle as my R answer.
# [Julia 0.6](http://julialang.org/), 55 bytes
```
x->inv([binomial(i,j)for i=(l=length(x)-1:-1:0),j=l])*x
```
[Try it online!](https://tio.run/##XYlBCoMwEADvfYXHXVEwwYp0ST8iHhRM3bCuIrbk96lHEeYyM@ErPDTJuxTLN@sPupF1XXgQ4CKgX/eMHYiTST/HDBFL8zqpsAhOesxj2nbWQxQ8dKZHfFz8SZbura2ptmQNmYrs@dIf "Julia 0.6 – Try It Online")
@Lynn's algorithm (inverse of Pascal matrix multiplied by input).
]