Inverse Deltas of an Array

17

1

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.

ATaco

Posted 2016-11-25T03:08:01.840

Reputation: 7 898

1I don't understand the recompile step? How do you get from -2, -1, 2, -6 to 1, -1, -2, 0, -6?? – Fogmeister – 2016-11-25T07:45:40.433

@Fogmeister you start from the same initial value and then apply these differences instead of the original ones. – Martin Ender – 2016-11-25T07:59:49.490

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 – 2016-11-25T08:16:32.050

@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 – 2016-11-25T08:19:57.747

1

@HaraldKorneliussen It's probably referring to this (and that's likely what everyone is assuming)

– Martin Ender – 2016-11-25T08:37:17.180

@Fogmeister You start from 1 3 4 2 8. Then 3 - 1 = 2, 4 - 3 = 1, 2 - 4 = -2, 8 - 2 = 6, gives 2 1 -2 6. You negate those to get -2 -1 2 -6. Then you start from 1 and apply these differences: 1 + (-2) = -1, -1 + (-1) = -2, -2 + 2 = 0, 0 + (-6) = -6, so you end up with 1 -1 -2 0 -6. – Martin Ender – 2016-11-25T08:39:30.477

does "any acceptable format" include outputting backwards? – FlipTack – 2016-11-25T21:12:07.913

also, you said the input would be signed integers at the beginning, and unsigned integers later on. – FlipTack – 2016-11-25T22:20:24.107

All these questions use one function sxs->s in list... – RosLuP – 2016-11-26T17:09:17.440

@Flp.Tkc Missed that, sorry. Signed was the intention, although none of the test cases have signed inputs. – ATaco – 2016-11-27T22:12:02.690

Answers

26

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.

Dennis

Posted 2016-11-25T03:08:01.840

Reputation: 196 637

1Well, pack it up. There's nothing to be done here except crawl away in defeat. – Steven H. – 2016-11-25T03:27:10.987

3Dennis just waits for me to post a question and Snipes me with these tiny Jelly Answers. I have no complaints. – ATaco – 2016-11-25T03:28:39.720

10

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).

Dennis

Posted 2016-11-25T03:08:01.840

Reputation: 196 637

7

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}.

Greg Martin

Posted 2016-11-25T03:08:01.840

Reputation: 13 940

Indeed, thanks—merely a typo. – Greg Martin – 2016-11-25T23:29:29.083

6

JavaScript (ES6), 21

Thx @Dennis

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

edc65

Posted 2016-11-25T03:08:01.840

Reputation: 31 086

That's... short. – ETHproductions – 2016-11-25T15:04:38.003

4

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

Emigna

Posted 2016-11-25T03:08:01.840

Reputation: 50 798

2

Python, 44 bytes

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

This uses the "Easier method".

James

Posted 2016-11-25T03:08:01.840

Reputation: 54 537

2

Pyth, 5 bytes

-LyhQ

Online Interpreter!

Steven H.

Posted 2016-11-25T03:08:01.840

Reputation: 2 841

2

R, 23 18 17 bytes

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

auto-vectorisation and default print to the rescue!

Jonathan Carroll

Posted 2016-11-25T03:08:01.840

Reputation: 211

Why not 2*x[1]-x instead? – Billywob – 2016-11-25T07:44:27.867

Had to leave something to optimise, right? (thank you) – Jonathan Carroll – 2016-11-25T07:48:55.133

2

Haskell, 20 19 bytes

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.

Renzeee

Posted 2016-11-25T03:08:01.840

Reputation: 599

save one byte: f(x:r)=x:map(2*x-)r – Christian Sievers – 2016-11-29T02:18:28.743

Thanks, I had tried several different approaches with @ and without, but didn't think of just putting x in front. – Renzeee – 2016-11-29T10:27:55.620

2

Ruby, 23 bytes

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

Not particularly original.

G B

Posted 2016-11-25T03:08:01.840

Reputation: 11 099

2

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
  )
}

Brad Gilbert b2gills

Posted 2016-11-25T03:08:01.840

Reputation: 12 713

2

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

Riley

Posted 2016-11-25T03:08:01.840

Reputation: 11 345

1

Pyke, 5 4 bytes

h}m-

Try it here!

Blue

Posted 2016-11-25T03:08:01.840

Reputation: 26 661

1

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,' ';

user59178

Posted 2016-11-25T03:08:01.840

Reputation: 1 007

Save one byte with a& instead of ''< and two bytes with _ instead of ' '. – Titus – 2017-03-15T07:05:07.430

1

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│
└───────┴────────────┴──────────────────┘

marinus

Posted 2016-11-25T03:08:01.840

Reputation: 30 224

1

Labyrinth, 34 bytes

?:_2*}
@    _
)\?_1"
,    ;
!`-}:{

Try it online!

Uses @Dennis's (2a - a, 2a - b, 2a - c, 2a - d) approach.

enter image description here

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

Robert Hickman

Posted 2016-11-25T03:08:01.840

Reputation: 661

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 – 2016-11-28T15:44:14.237

@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 – 2016-11-28T15:49:51.867

1

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.

Martin Ender

Posted 2016-11-25T03:08:01.840

Reputation: 184 808

These solutions are great. It's great to examine these and learn about thinking in Labyrinth. – Robert Hickman – 2016-11-28T22:10:05.980

0

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";
}

Karl Napf

Posted 2016-11-25T03:08:01.840

Reputation: 4 131

0

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.

Roman Gräf

Posted 2016-11-25T03:08:01.840

Reputation: 2 915

There's also http://cjam.tryitonline.net, which base64 encodes all fields. Both interpreters give me an error though.

– Dennis – 2016-11-25T20:35:21.170

0

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~-_

FlipTack

Posted 2016-11-25T03:08:01.840

Reputation: 13 242

0

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"

Denis Ibaev

Posted 2016-11-25T03:08:01.840

Reputation: 876

0

Dyalog APL, 5 bytes

-+2×⊃

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

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

ngn

Posted 2016-11-25T03:08:01.840

Reputation: 11 449

0

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)

orion

Posted 2016-11-25T03:08:01.840

Reputation: 3 095

0

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]

More readable:

@(map @
  - (
    * 2 get 0 #1
  ) #0
) #0

Mama Fun Roll

Posted 2016-11-25T03:08:01.840

Reputation: 7 234