Reverse Deltas of an Array

A continuation of Inverse Deltas of an Array

Your task is to take an array of signed 32 bit integers, recompile it with its deltas reversed.

Example

The List,

18  19  17  20  16

has the deltas:

1  -2   3  -4

which, when reversed, yields:

-4   3  -2   1

then when recompiled, using yields:

18  14  17  15  16

which should be your return value.

Recompiling consists of taking the C, which is the first value of the array. In this case, 18, and applying the deltas to it in order. So 18 + -4 gives 14, 14 + 3 gives 17, and so on.

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 reversing method.

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

Test Cases

1 2 3 4 5      -> 1 2 3 4 5
18 19 17 20 16 -> 18 14 17 15 16
5 9 1 3 8 7 8  -> 5 6 5 10 12 4 8
6 5 4 1 2 3    -> 6 7 8 5 4 3

Notes

• As stated in above, you will always receive at least 1 input, and no more than 9.
• The first and last number of your output, will always match that of the input.
• Only Standard Input Output is accepted
• Standard loopholes apply
• This is , so the lowest byte-count wins!
• Have fun!

And the winner is...

Dennis! Who firstly took the first place, then beat himself with a shorter solution, giving himself both the first and second place!

Honorable mention to ais523 with their Jelly, that if not for Dennis getting in just before them, would have held the second place.

• These delta challenges have only proven how unneeded deltas are in mathematics. – ATaco Dec 5 '16 at 1:02
• how unneeded deltas are in mathematics One of the most important branches of mathematics is based on (infinitesimally small) deltas – Luis Mendo Dec 5 '16 at 1:13
• I am still a not happy chappy – ATaco Dec 5 '16 at 1:21
• I can't C a mathematical challenge on ppcg...:P – Mukul Kumar Dec 5 '16 at 13:37

Jelly, 5 bytes

.ịS_Ṛ

This uses the algorithm from Glen O's Julia answer.

Try it online!

How it works

.ịS_Ṛ  Main link. Argument: A (array)

.ị     At-index 0.5; retrieve the values at the nearest indices (0 and 1). Since
indexing is 1-based and modular, this gives the last and first element.
S    Compute their sum.
Ṛ  Yield A, reversed.
_   Subtract the result to the right from the result to the left.
• Dennis Please – Nic Hartley Dec 5 '16 at 7:18

Jelly, 6 bytes

I;ḢṚ+\

Try it online!

How it works

I;ḢṚ+\  Main link. Argument: A (array)

I       Increments; compute the deltas of A.
Ḣ     Head; yield the first element of A.
;      Concatenate the results to both sides.
Ṛ    Reverse the resulting array.
+\  Compute the cumulative sum of the reversed array.
• Dennis Please – ATaco Dec 5 '16 at 0:51
• Looks like you beat me by a few minutes. Surprisingly, our programs aren't even identical (you have where I have U). I don't know if that makes them different enough to not consider duplicates. – user62131 Dec 5 '16 at 1:02
• @ais523 U vectorizes while does not, but their behavior for flat arrays is identical. – Dennis Dec 5 '16 at 1:04
• I guess I'll delete my answer, then (whilst being a little annoyed since I managed to come up with the "right" answer on my own, and the only real issue here is that someone else managed to find the same answer first). – user62131 Dec 5 '16 at 1:09
• In what ASCII format does it come out as 6 bytes? Pluma on Xubuntu says it's 10 bytes, and Julia stores as 0x1e22 and as 0x1e5a, each of which therefore requires 3 bytes. – Glen O Dec 6 '16 at 5:45

Julia, 24 bytes

!x=x[end]+x[]-reverse(x)

This is the "clever" way to solve the problem. The negative reverse of the array has the "deltas" reversed, and then you just need to fix the fact that it starts/ends at the wrong places.

Snowman 1.0.2, 72 bytes

((}#0AaGwR#wRaCaZ0NdEaN0AaG:dU,0aA|1aA,nS;aM0wRaC|#0aA*|:#nA*#;aM*))

Try it online!

This is a subroutine that takes input from and outputs to the current permavar.

((
}       enable variables b, e, and g
#       store the input in variable b
0AaG    remove the first element (take indices > 0)
wR      wrap the array in another array
#wRaC  concatenate with the original input array
aZ      zip (transpose); we now have pairs of elements
0NdE   obtain the number -1 (by decrementing 0)
aN     reverse the zipped array
0AaG    remove first (there is one fewer delta than array elements)
:       map over the array of pairs:
dU     duplicate; we now have b=[x,y] e=[x,y]
,0aA   move the copy and get the first element; b=x g=[x,y]
|1aA   get the second element from the copy; b=y g=x
,nS    subtract; we now have b=y-x which is returned from the map
;aM     (map)
0wRaC  prepend a zero (in preparation for the next step)
|#0aA   get the first element of the original array
*       store this in the permavar
|:      map over the array of deltas with 0 prepended:
#       store the permavar in e
nA      add the delta and the permavar
*#      make this the new value of the permavar
;aM     (map)
*       "return" the resulting array from the subroutine
))

JavaScript (ES6), 45 37 bytes

a=>a.reverse(z=a).map(e=>z+a-e)

Port of @JHM's Mathematica answer. (I'm sure I could have derived it myself, but not at this time of night.) Edit: Saved 8 bytes thanks to @edc65.

• Is there a reason why you need [... and ]? – Mama Fun Roll Dec 5 '16 at 1:13
• @MamaFunRoll otherwise it would modify a, which is used later in the program – Conor O'Brien Dec 5 '16 at 4:13
• Oh right, forgot about that :P – Mama Fun Roll Dec 5 '16 at 4:19
• 37: a=>a.reverse(z=a).map(e=>z+a-e) – edc65 Dec 5 '16 at 10:07
• @edc65 Bah, I was awake enough last night to consider z=a, but I forgot to remove the [...] and (,i,b). – Neil Dec 5 '16 at 11:21

Mathematica, 23 bytes

#&@@#+Last@#-Reverse@#&

Unnamed function. The result is simply: reverse( (first element) + (last element) - (each element) ).

Python 2, 967454 44 bytes

lambda l:[l+l[-1]-j for j in l][::-1]

Input is given as an array surrounded by square brackets. Output is in the same format.

Thanks to @Kade for saving 22 42 bytes by using a much more simple method than whatever I was doing before!

Thanks to @Sherlock9 for saving 10 bytes by eliminating the index counter from the list comprehension!

Great, now if I golf it anymore I'll get the "crossed out 44 is still 44" problem. ;_;

• What about lambda l:[l+l[-1]-l[i]for i in range(len(l))][::-1] for 54 bytes? :) (Credits to Glen O. for the calculation) – Kade Dec 5 '16 at 14:52
• Oh wow, how did I not figure that out. Thanks! :) – HyperNeutrino Dec 5 '16 at 14:54
• Alex, you can just use that lambda function as your answer :) – Kade Dec 5 '16 at 15:06
• What. Oh. Okay, thanks! :) – HyperNeutrino Dec 5 '16 at 15:19
• Instead of l[i]for i in range(len(l)), you can use j for j in l to save 14 bytes. – Sherlock9 Dec 5 '16 at 20:10

05AB1E, 8 bytes

¬s¤sR(++

Try it online!

Translation of my MATL answer, second approach.

¬    % Implicit input. Head, without consuming the input
s    % Swap
¤    % Tail, without consuming the input
s    % Swap
R(   % Reverse and negate
++   % Add head and tail of input to reversed and negated input. Implicitly display
• Smarter than what I was trying: ¬s¥Rvy)} – Magic Octopus Urn Dec 7 '16 at 22:44

R, 37 30 bytes

Edit: Now using the approach in Glen O's Julia answer

x=scan();x+tail(x,1)-rev(x)

Old:

x=scan();cumsum(c(x,rev(diff(x))))

Reads input, compute deltas, concatenate with first element and calculate the cumulative sum.

MATL, 8 bytes

1)GdPhYs

Try it online!

This is direct application of the definition. Consider input [18 19 17 20 16] as an example.

1)     % Implicit input. Get its first entry
% STACK: 18
G      % Push input again
% STACK: 18, [18 19 17 20 16]
d      % Consecutive differences
% STACK: 18, [1 -2 3 -4]
P      % Reverse
% STACK: 18, [-4 3 -2 1]
h      % Concatenate
% STACK: [18 -4 3 -2 1]
Ys     % Cumulative sum. Implicitly display
% STACK: [18 14 17 15 16]

Different approach, same byte count:

P_G5L)s+

Try it onllne!

Reversed and negated array plus the first and last entries of the original array.

P_     % Implicit inut. Reverse and negate
G      % Push input again
5L)s   % Sum of first and last entries
+      % Add to reversed and negated array. Implicitly display

Japt, 8 bytes

Ô®nUÌ+Ug

Run it online

• Exactly what I had :) – Shaggy Feb 25 at 16:20

sM._+hQ_.+

아희(Aheui), 3 * 21 chars + 2 "\n" = 65 bytes

빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔

Assumes input in stack 아. The output will be stored in stack 안.

If you want to try this code:

At the end of the first line of this code, add the character length(n)-times (i.e. if the input is 7 integers, insert it 7 times). For each prompt, type one integer:

어우
우어
빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔

Try it here! (copy and paste the code)

Example

For 1, 2, 3, 4, 5:

어우벙벙벙벙벙
우어
빪쑥쌳텆슉폎귁삯씬희
뿓팤팧쎢싺솎
싺싹삭당뽔

and then type 1, 2, 3, 4, and 5 (there will be 5 prompts).

Alternative Version (65 bytes)

빠쑥쌳터슉펴ㅇ삯씬희
뿌파파쎢싺솎
싺싹삭다뽀
• Why don't you just say 65 bytes in UTF-8 or something? – mbomb007 Dec 5 '16 at 15:13
• @mbomb007 because some people don't know Korean characters are 3 bytes each. – JungHwan Min Dec 5 '16 at 15:31

C# 42 bytes

Takes an int[] and returns an IEnumerable<int>.

a=>a.Select(v=>a+a.Last()-v).Reverse();

(This is actually just a ported version of JHM's version..)

TSQL, 200 bytes

Table variable used as input

DECLARE @ table(a int, b int identity)

INSERT @ values(5),(9),(1),(3),(8),(7),(8);

WITH c as(SELECT*,rank()over(order by b desc)z FROM @)SELECT g+isnull(sum(-f)over(order
by b),0)FROM(SELECT sum(iif(c.b=1,c.a,0))over()g,d.a-lead(d.a)over(order by d.b)f,c.b
FROM c,c d WHERE c.b=d.z)d

Try it out

PHP, 6056 52 bytes

-4 bytes thanks to @user59178

for($a=$argv;--$argc;)echo$a+end($a)-$a[$argc],_; operates on command line arguments, uses underscore as separator. Run with php -r '<code>' <space separated numbers> • Is there a reason why you don't just use$n as the control variable? I tried a version like that and it was 4 bytes shorter and seemed to work. – user59178 Dec 5 '16 at 15:39

Perl 6,  48 33  30 bytes

{[\+] .,|.reverse.rotor(2=>-1).map({[-] @_})}
{.reverse.map: {.+.[*-1]-$^a}} {[R,] .map: {.+.[*-1]-$^a}}

Try it

Expanded:

{  # bare block lambda with implicit parameter ｢$_｣ [R,] # reduce the following using the comma operator [R]eversed # (short way to do the same thing as ｢reverse｣) .map: # map the input (implicit method call on ｢$_｣

{              # bare block lambda with placeholder parameter ｢$a｣ .[ 0 ] # the first value of ｢$_｣ (implicit “method” call)
+ .[ * - 1 ] # add the last value of ｢$_｣ (implicit “method” call) -$^a    # declare the parameter and subtract it from the above
}
}

The *-1 is also a lambda expression of type WhateverCode, where the * is the only positional parameter.

• Explanation for those that don't speak perl? – Cyoce Mar 15 '17 at 4:39
• @Cyoce Added for the shortest version. This would need explaining to someone that knew Perl 5 as well. In case you were wondering [\+] from the first example, is triangle reduce [\+] 3,-1,1,-5(3,2,3,-2) and [\,] 3,-1,1,-5((3,), (3,-1), (3,-1,1), (3,-1,1,-5)) – Brad Gilbert b2gills Mar 15 '17 at 15:50

Julia 0.4, 32 bytes

!x=[x[];x|>diff|>flipud]|>cumsum

Try it online!

BASH, 71 bytes

s=$1 echo$s
for i in seq ${#@} -1 2;{ echo$[s=s+${!i}-${@:i-1:1}]
}

C++14, 103 bytes

As unnamed lambda, requiring its input to have rbegin, rend, back and push_back like the containers vector, deque or list.

Using the approach from Glen O's Julia answer

[](auto c){decltype(c)d;for(auto i=c.rbegin()-1;++i!=c.rend();)d.push_back(c+c.back()-*i);return d;}

Ungolfed and usage:

#include<iostream>
#include<vector>

//declare generic function, return is deduced automatically
auto f=[](auto c){
//create fresh container of the same type as input
decltype(c)d;

//iterate through the reverse container
for(auto i=c.rbegin()-1;++i!=c.rend();)
//add the first and last element minus the negative reverse
d.push_back(c+c.back()-*i);
return d;
}
;

int main(){
std::vector<int> a={18,  19,  17,  20,  16};
auto b = f(a);
for(auto&x:b)
std::cout << x << ", ";
std::cout<<"\n";
}

Uses the same logic as JHM:

f a=map(head a+last a-)$reverse a Quite readable as well. • You can save 3 bytes by using (!!0) for head and using (<$>) for map: Try it online! – ბიმო Oct 6 '18 at 14:54

Convex, 10 bytes

_î\(@¥+¡p;

Try it online!

Clojure, 101 bytes

(fn[c](conj(map #(-(first c)%)(reductions +(reverse(map #(apply - %)(partition 2 1 c)))))(first c))))

Pretty much follows the description:

(def f (fn[c]
(conj
(->> c
(partition 2 1)
(map #(apply - %))
reverse
(reductions +)
(map #(-(first c)%)))
(first c))))

Java 7, 96 bytes

int[]c(int[]a){int l=a.length,i=1,r[]=a.clone();for(;i<l;r[i]=r[i-1]+a[l-i]-a[l-++i]);return r;}

Explanation:

int[] c(int[] a){     // Method with integer-array parameter and integer-array return-type
int l=a.length,     //  Length of input array
i=1,            //  Index (starting at 1, although Java is 0-indexed)
r[]=a.clone();  //  Copy of input array
for(; i<l;          //  Loop over the array
r[i] =            //   Replace the value at the current index in the copied array with:
r[i-1]          //    The previous value in this copied array
+ a[l - i]      //    plus the opposite value in the input array
- a[l - ++i])   //    minus the value before the opposite value in the input array (and increase the index)
;                   //  End the loop (implicit / no body)
return r;           //  Return the result array
}                     // End of method

Test code:

Try it here.

class M{
static int[]c(int[]a){int l=a.length,i=1,r[]=a.clone();for(;i<l;r[i]=r[i-1]+a[l-i]-a[l-++i]);return r;}

public static void main(String[] a){
System.out.println(java.util.Arrays.toString(c(new int[]{ 18,19,17,20,16 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 1,2,3,4,5 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 5,9,1,3,8,7,8 })));
System.out.println(java.util.Arrays.toString(c(new int[]{ 6,5,4,1,2,3 })));
}
}

Output:

[18, 14, 17, 15, 16]
[1, 2, 3, 4, 5]
[5, 6, 5, 10, 12, 4, 8]
[6, 7, 8, 5, 4, 3]

APL (Dyalog Unicode), 11 bytesSBCS

Anonymous tacit prefix function.

+\⊃,∘⌽2-⍨/⊢

Try it online!

+\ cumulative sum of

the first element of the argument

, followed
by
the reversal of

2-⍨/ the pairwise difference of

the argument