24
\$\begingroup\$

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.

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

28 Answers 28

12
\$\begingroup\$

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.
\$\endgroup\$
6
  • 7
    \$\begingroup\$ Dennis Please \$\endgroup\$
    – ATaco
    Dec 5, 2016 at 0:51
  • \$\begingroup\$ 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. \$\endgroup\$
    – user62131
    Dec 5, 2016 at 1:02
  • \$\begingroup\$ @ais523 U vectorizes while does not, but their behavior for flat arrays is identical. \$\endgroup\$
    – Dennis
    Dec 5, 2016 at 1:04
  • 4
    \$\begingroup\$ 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). \$\endgroup\$
    – user62131
    Dec 5, 2016 at 1:09
  • \$\begingroup\$ 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. \$\endgroup\$
    – Glen O
    Dec 6, 2016 at 5:45
10
\$\begingroup\$

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.
\$\endgroup\$
1
  • 7
    \$\begingroup\$ Dennis Please \$\endgroup\$
    – anon
    Dec 5, 2016 at 7:18
8
\$\begingroup\$

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.

\$\endgroup\$
7
\$\begingroup\$

Snowman 1.0.2, 72 bytes

((}#0AaGwR#`wRaCaZ`0NdE`aN0AaG:dU,0aA|1aA,nS;aM`0wRaC|#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
))
\$\endgroup\$
6
\$\begingroup\$

JavaScript (ES6), 45 37 bytes

a=>a.reverse(z=a[0]).map(e=>z+a[0]-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.

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

Mathematica, 23 bytes

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

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

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

Python 2, 96 74 54 44 bytes

lambda l:[l[0]+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. ;_;

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

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
\$\endgroup\$
1
  • \$\begingroup\$ Smarter than what I was trying: ¬s¥Rvy)} \$\endgroup\$ Dec 7, 2016 at 22:44
3
\$\begingroup\$

R, 37 30 bytes

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

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

Old:

x=scan();cumsum(c(x[1],rev(diff(x))))

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

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

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
\$\endgroup\$
2
\$\begingroup\$

Japt, 8 bytes

Ô®nUÌ+Ug

Run it online

\$\endgroup\$
1
  • \$\begingroup\$ Exactly what I had :) \$\endgroup\$
    – Shaggy
    Feb 25, 2019 at 16:20
1
\$\begingroup\$

Pyth - 10 bytes

sM._+hQ_.+

Test Suite.

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

아희(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)

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

C# 42 bytes

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

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

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

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

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

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

PHP, 60 56 52 bytes

-4 bytes thanks to @user59178

for($a=$argv;--$argc;)echo$a[1]+end($a)-$a[$argc],_;

operates on command line arguments, uses underscore as separator. Run with
php -r '<code>' <space separated numbers>

\$\endgroup\$
1
  • 1
    \$\begingroup\$ 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. \$\endgroup\$
    – user59178
    Dec 5, 2016 at 15:39
1
\$\begingroup\$

Perl 6,  48 33  30 bytes

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

\$\endgroup\$
2
  • \$\begingroup\$ Explanation for those that don't speak perl? \$\endgroup\$
    – Cyoce
    Mar 15, 2017 at 4:39
  • \$\begingroup\$ @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)) \$\endgroup\$ Mar 15, 2017 at 15:50
1
\$\begingroup\$

Desmos, 34 bytes

f(l)=l[1]+l[k]-l[k...1]
k=l.length

Uses the trick from the Mathematica answer. Go check that answer out too!

Try It On Desmos!

Try It On Desmos! - Prettified

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

Factor, 39 bytes

[| s | s first s last + s reverse n-v ]

Try it online!

A rare problem where local variables win out over stack shuffling. Note that s is the only variable; n-v is the name of a word that subtracts a vector from a number. Uses the same logic as JungHwan Min's Mathematica answer.

\$\endgroup\$
0
\$\begingroup\$

Julia 0.4, 32 bytes

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

Try it online!

\$\endgroup\$
0
0
\$\begingroup\$

BASH, 71 bytes

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

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[0]+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[0]+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";
}
\$\endgroup\$
0
\$\begingroup\$

Haskell, 33 bytes

Uses the same logic as JHM:

f a=map(head a+last a-)$reverse a

Quite readable as well.

\$\endgroup\$
1
  • \$\begingroup\$ You can save 3 bytes by using (!!0) for head and using (<$>) for map: Try it online! \$\endgroup\$ Oct 6, 2018 at 14:54
0
\$\begingroup\$

Convex, 10 bytes

_î\(@¥+¡p;

Try it online!

\$\endgroup\$
0
\$\begingroup\$

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))))
\$\endgroup\$
0
\$\begingroup\$

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]
\$\endgroup\$
0
\$\begingroup\$

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

\$\endgroup\$
0
\$\begingroup\$

Husk, 9 bytes

m`-§+←→¹↔

Try it online!

\$\endgroup\$

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.