# Inverse Deltas of an Array

Your task is to, given an array of signed 32 bit integers, recompile it with its inverse deltas. For example, the list

1  3  4  2  8


holds the deltas:

  2  1 -2  6


which are then negated, yielding:

 -2 -1  2 -6


and recompiled, yielding:

1 -1 -2  0 -6


as the final result.

## Input/Output

You will be given a list/array/table/tuple/stack/etc. of signed integers as input through any standard input method.

You must output the modified data once again in any acceptable form, following the above delta inversion method.

You will receive N inputs where 0 < N < 10 where each number falls within the range -1000 < X < 1000

## Test Cases

5 6 7 8          -> 5 4 3 2
1 3 4 2 8        -> 1 -1 -2 0 -6
32 18 25 192 199 -> 32 46 39 -128 -135


## Notes

• You are not restricted to the delta based method: if you can work out the easier method (which shouldn't be too hard), you're free to use it.
• As stated in above, you will always receive at least 1 input, and no more than 9.
• The first number of the output must always be the first number of the input, if this is not the case, your method is incorrect.
• Only Standard Input Output is accepted
• Standard loopholes apply
• This is , so the lowest byte-count wins!
• Have fun!

## We have a winner.

Dennis's Jelly Answer at a Tiny 3 Bytes has taken home the gold, due to the fact that I am under the impression it cannot be beaten.

I was mildly disappointed I didn't get to see an answer based on the original spec, however, I may later put a bounty on precisely that.

• I don't understand the recompile step? How do you get from -2, -1, 2, -6 to 1, -1, -2, 0, -6?? – Fogmeister Nov 25 '16 at 7:45
• @Fogmeister you start from the same initial value and then apply these differences instead of the original ones. – Martin Ender Nov 25 '16 at 7:59
• Standard Input Output - I haven't heard that used in a challenge before, but I infer that it does NOT mean stdin/stdout, since otherwise all replies here seem to be wrong. I guess it means that you can't take input as Church numerals or something? Anyway, if that's what it means, it should probably be called something else since standard output/input has another meaning as well. – Harald Korneliussen Nov 25 '16 at 8:16
• @MartinEnder 1+0=1, 3-2=-1?, 4-1=-2?? That's what I thought but those numbers don't add up. Oh! Never mind. I just saw it. You create a new array starting at the original value but with the new differences. So 1 with a diff of -2 goes to -1, then with a diff of -1 this goes to -2 and so on. – Fogmeister Nov 25 '16 at 8:19
• @HaraldKorneliussen It's probably referring to this (and that's likely what everyone is assuming) – Martin Ender Nov 25 '16 at 8:37

# Jelly, 7 3 bytes

ḤḢ_


Try it online!

### Background

The deltas of (a, b, c, d) are b - a, c - b, and d - c. Cumulatively reducing (a, b - a, c - b, d - c) by subtractiong yields a - (b - a) = 2a - b, 2a - b - (c - b) = 2a - c, and 2a - c - (d - c) = 2a - d, so the correct result is (2a - a, 2a - b, 2a - c, 2a - d).

### How it works

ḤḢ_  Main link. Argument: A (array)

Ḥ    Unhalve; multiply all integers in A by 2.
Ḣ   Head; extract first element of 2A.
_  Subtract the elements of A from the result.

• Well, pack it up. There's nothing to be done here except crawl away in defeat. – Steven H. Nov 25 '16 at 3:27
• Dennis just waits for me to post a question and Snipes me with these tiny Jelly Answers. I have no complaints. – ATaco Nov 25 '16 at 3:28

# Python 2, 30 bytes

lambda x:[x[0]*2-n for n in x]


Test it on Ideone.

### How it works

The deltas of (a, b, c, d) are b - a, c - b, and d - c. Cumulatively reducing (a, b - a, c - b, d - c) by subtractiong yields a - (b - a) = 2a - b, 2a - b - (c - b) = 2a - c, and 2a - c - (d - c) = 2a - d, so the correct result is (2a - a, 2a - b, 2a - c, 2a - d).

# Mathematica, 8 bytes

2#-{##}&


Unnamed function taking an indeterminate number of arguments. This uses an "easy" way: negates the entire list and adds twice the (original) first element.

Called for example like 2#-{##}&[1,3,4,2,8]; returns a list like {1,-1,-2,0,-6}.

• Indeed, thanks—merely a typo. – Greg Martin Nov 25 '16 at 23:29

# JavaScript (ES6), 21

Thx @Dennis

l=>l.map(v=>l[0]*2-v)

• That's... short. – ETHproductions Nov 25 '16 at 15:04

# 05AB1E, 4 bytes

¬·s-


Try it online! or as a Test suite

Explanation

¬     # head of input list
·    # multiplied by 2
s   # swap with input list
-  # subtract


# Python, 44 bytes

lambda l:[l[0]]+[x-(x-l[0])*2for x in l[1:]]


This uses the "Easier method".

# Pyth, 5 bytes

-LyhQ


Online Interpreter!

# R, 2318 17 bytes

x=scan();2*x[1]-x


auto-vectorisation and default print to the rescue!

• Why not 2*x[1]-x instead? – Billywob Nov 25 '16 at 7:44
• Had to leave something to optimise, right? (thank you) – Jonathan Carroll Nov 25 '16 at 7:48

# Ruby, 23 bytes

->l{l.map{|x|l[0]*2-x}}


Not particularly original.

# Perl 6,  40  16 bytes

{[\+] .[0],|.rotor(2=>-1).map({[-] @_})}

{.map(.[0]*2-*)}


## Expanded:

{ # bare block lambda with single implicit parameter ｢$_｣ ( input is a List ) [\[+]] # triangle reduce the following using ｢&infix:<+>｣ .[0], # the first value |( # Slip this list into outer one ( Perl 6 doesn't auto flatten ) .rotor( 2 => -1 ) # take the input 2 at a time, backing up 1 .map({ [-] @_ }) # reduce the pairs using ｢&infix:<->｣ ) }  { # bare block lambda with single implicit parameter ｢$_｣ ( input is a List )

.map(          # map over the inputs
.[0] * 2 - * # take the first value multiply by 2 and subtract the current value
#          ^- this makes the statement a WhateverCode, and is the input
)
}


# Brain-Flak, 76 Bytes

([][()]){{}(({})<(({}){}[{}]<>)<>>)([][()])}{}({}<<>([]){{}({}<>)<>([])}<>>)


Try it Online!

Explanation:

Part 1:
(      )                                        # Push:
[]                                             # the height of the stack
[()]                                         # minus 1
{                                  }    # While the height - 1 != 0:
{}                                     # Pop the height
(({})<                               # Hold onto the top value, but put it back.
# This ensures that the top value is always
# what was the first element of input
(            )                 # Push:
({}){}                        # Top * 2
[{}]                    # minus the next element
<> <>               # onto the other stack

>)             # Put back the element we held onto.
(      )     # Push:
[]          # The height of the stack
[()]      # Minus 1
{}  # Pop the counter used for the height
Part 2:
({}<                                            # Hold onto the top element.
# This was the first number for input
# so it needs to end up on top
<>                                          # Switch stacks
([])                                      # Push the height of the stack
{              }                      # While the height != 0:
{}                                   # Pop the height
(    )                             # Push:
{}                                # The top element of this stack
<>                              # onto the other stack
<>                           # and switch back
([])                       # Push the new height of the stack
<>                    # After every element has switched stacks
# (which reverses their order),
# switch stacks
>)                  # Push the first element back on


f(x:r)=x:map(2*x-)r


Same solution as Dennis, thank you for your idea of 2a - x.

Saved one byte thanks to Christian Severs.

• save one byte: f(x:r)=x:map(2*x-)r – Christian Sievers Nov 29 '16 at 2:18
• Thanks, I had tried several different approaches with @ and without, but didn't think of just putting x in front. – Renzeee Nov 29 '16 at 10:27

## Pyke, 5 4 bytes

h}m-


Try it here!

# PHP, 48 bytes

for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' ';  Using the technique from Dennis. Use like: php -r "for(;''<$c=$argv[++$i];)echo-$c+2*$a=$a??$c,' ';" 1 3 4 2 8


Non-Dennis 55 byte version:

for(;''<$c=$argv[++$i];$l=$c)echo$a+=($l??$c*2)-$c,' ';  • Save one byte with a& instead of ''< and two bytes with _ instead of ' '. – Titus Mar 15 '17 at 7:05 # APL, 8 bytes +\⊃,2-/+  Explanation: +\ ⍝ running sum of ⊃ ⍝ first item of list , ⍝ followed by 2-/ ⍝ differences between every pair in + ⍝ input list  Test cases:  ( +\⊃,2-/+ ) ¨ (5 6 7 8) (1 3 4 2 8) (32 18 25 192 199) ┌───────┬────────────┬──────────────────┐ │5 4 3 2│1 ¯1 ¯2 0 ¯6│32 46 39 ¯128 ¯135│ └───────┴────────────┴──────────────────┘  # Labyrinth, 34 bytes ?:_2*} @ _ )\?_1" , ; !-}:{  Try it online! Uses @Dennis's (2a - a, 2a - b, 2a - c, 2a - d) approach. The yellow tiles are for control flow. In this 2D programming language, the program starts at the top-left-most tile moving east to start. At junctions, the direction is determined by the sign of the top of the main stack. Blank tiles are walls. ## Green This section saves 2a to the auxilary stack. • ? Get the first number and push it to the top of the main stack • : Duplicate the top of the stack • _2 Push two to the top of the stack • * Pop y, pop x, push x*y • } Move the top of the main stack to the top of the auxilary stack. • _ Push zero to the top of the stack ## Orange This section subtracts 2a from the current number, negates the result, outputs the result, gets the next character (the delimeter), exits if EOF, outputs a newline, gets the next number. • " Noop. If coming from the north, the top of the stack will be zero and the program will continue south. If coming from the west, the top of the stack will be one and the program will turn right (continuing south) • ; Discard the top of the stack. As the zero or one is only used for control flow, we need to discard these • { Move the top of the auxilary stack (2a) to the top of the main stack • : Duplicate the top of the main stack • } Move the top of the main stack to the top of the auxilary stack • - Pop y, pop x, push x-y • \ Negate the top of the stack. This and the previous three operations have the effect of-(x-2a) = 2a-x • ! Pop the top of the stack and output it as a number • , Push the next character (which will be the delimiter) or negative one if EOF • ) Increment the top of the stack. If the last character is EOF, then the top of the stack will now be zero and the program will continue straight to the @ and exit. If the last character was a delimeter, then the top of the stack will be positive causing the program to turn right and continue east to the \ • \ Output a newline • ? Get the next number • _1 Push one to the top of the stack in order to turn right at the junction • Huh, this reminds me that I also solved this challenge but completely forgot to post the solutions. I've got three different solutions at 24 bytes (and I'm pretty sure they aren't optimal), so I guess I'll give you a couple of days or so to match or beat that before I post mine. Nice work, still! :) – Martin Ender Nov 28 '16 at 15:44 • @MartinEnder, no need to wait on me. I doubt I'll be able to think of a better solution any time soon. I'm still getting used to stack-based problem solving. I'm just enjoying learning a new way to think about programming. – Robert Hickman Nov 28 '16 at 15:49 ## Labyrinth, 24 bytes +:}:? } <}}?;%):,\!-{:{>  Input and output format are linefeed-separate lists (although the input format is actually a lot more flexible). The program terminates with an error. Try it online! I've got two other solutions at this byte count, which work basically the same but use somewhat different control flow. :+:}:? { ,}-! ? { :";\@  {:+:}:? _ <>__-?:;%):,\!  ### Explanation The instruction pointer (IP) starts moving east along the first line, but all the commands before the ? are basically no-ops on the global state, since we're not using stack depth commands anywhere. So the code really starts at the ? going west, since the IP turns around when it hits the dead end. The code therefore starts with the following linear bit of code: ?:}:+}  This simply sets us up with a copy of 2a to use the [2a - a, 2a - b, 2a - c, ...] formula. ? Read first integer a. :} Move a copy off to the auxiliary stack. :+ Multiply a by 2 (by adding it to itself). } Move that off to the auxiliary stack as well.  We now enter the main loop of the program, using a fairly standard trick to loop through a single line of code: <...>  Note that the stack will be empty whenever we hit the < so we know we'll get zeros there. The < then rotates the entire line left, taking the IP with it, so we get this: ...><  The IP then has to move left, where the > shifts the line back into its original place (to prepare it for the next iteration). Then the line is simply executed from right to left, so a single loop iteration is this: {:{-!\,:)%;?}}  The catch when working with a loop of this type is that you can't work with any form of conditional execution, since Labyrinth doesn't have a way to skip code. Therefore, we will terminate the program with a division by zero when we hit EOF. Here is a breakdown of each loop iteration. {: Pull 2a back to the main stack and make a copy. { Pull the latest value i of the input list back to main as well. - Compute 2a-i/ !\ Print it with a trailing linefeed. , Read a character. If there are input elements left, this will be some form of separator character, and therefore a positive value x. However, at the end of the program, this will give -1. :) Make an incremented copy. % Try to to compute x%(x+1). This will error out at EOF. ; Discard the result of the division. ? Read the next input value. }} Move that and the remaining copy of 2a back to the auxiliary stack.  • These solutions are great. It's great to examine these and learn about thinking in Labyrinth. – Robert Hickman Nov 28 '16 at 22:10 # C++14, 36 bytes As unnamed lambda modifying its input: [](auto&c){for(auto&x:c)x=2*c[0]-x;}  Using the technique from Dennis. Works for any container like int[] or vector<int>. Usage: #include<iostream> auto f= [](auto&c){for(auto&x:c)x=2*c[0]-x;} ; int main(){ int a[] = {1, 3, 4, 2, 8}; f(a); for(auto&x:a) std::cout << x << ", "; std::cout<<"\n"; }  # CJam, 16 bytes Input format: [1 2 3 4]. Uses the easy formula. l~_(2*/;a/,@@*.-  Explanation: l~_(2*/;a/,@@*.- l~_ e#Read input twice into an array. Stack: [1 2 3 4] [1 2 3 4] ( e#Get first element of the array. Stack: [1 2 3 4] [2 3 4] 1 2* e#Multiply by two. Stack: [1 2 3 4] [2 3 4] 2 /; e#Discard second element. Stack: [1 2 3 4] 2 a e#Wrap into an array. Stack: [1 2 3 4] [2] /, e#Rotate and get length. Stack: [2] [1 2 3 4] 4 @@ e#Rotate twice. Stack: [1 2 3 4] 4 [2] * e#Repeat len times. Stack: [1 2 3 4] [2 2 2 2] .- e#Vectorized substraction. Stack: [-1 0 1 2] e#Implictly print  Sorry for no test link. I guess SE don't like it's links with brackets inside. • There's also cjam.tryitonline.net, which base64 encodes all fields. Both interpreters give me an error though. – Dennis Nov 25 '16 at 20:35 # Pushy, 9 bytes {&}2*K~-_  Give arguments as comma-seperated values on cmd line: $ pushy invdeltas.pshy 1,3,4,2,8. Here's the breakdown, with example stack:

           % Implicit: Input on stack              [1, 3, 4, 2, 8]
{&}        % Copy first item, put at end of stack  [1, 3, 4, 2, 8, 1]
2*      % Multiply by 2                         [1, 3, 4, 2, 8, 2]
K~    % Negate everything on stack            [-1, -3, -4, -2, -8, -2]
-   % Subtract last item from all           [1, -1, -2, 0, -6]
_  % Print whole stack


Note: this can be 8 bytes if backwards output is allowed: @&2*K~-_

# Perl, 26 + 3 (-pla flag) = 29 bytes

$_="@{[map$F[0]*2-$_,@F]}"  or $_=join$",map$F[0]*2-$_,@F  Using: perl -plae '$_="@{[map$F[0]*2-$_,@F]}"' <<< "32 18 25 192 199"


# Dyalog APL, 5 bytes

this is a 5-train, it parses like two nested 3-trains ("forks"): -+(2×⊃)

reads like: the negation (-) of the whole array plus (+) twice (2×) the first element (⊃)

# ised, 11 bytes

2*$1_0-$1


Invocation: ised --l 'file with input.txt' '2*$1_0-$1

(edit: corrected by stealing the algebra from Dennis)

# Wonder, 17 bytes

@->#@- *2:0#1#0#0


Not sure why I didn't post this earlier. Usage:

(@->#@- *2:0#1#0#0)[5 6 7 8]


@(map @