配列の逆デルタ


23

配列の逆デルタ

配列の逆デルタの続き

あなたの仕事は、符号付き32ビット整数の配列を取得し、そのデルタを逆にして再コンパイルすることです。

リスト、

18  19  17  20  16

デルタがあります:

   1  -2   3  -4

逆にすると、次の結果が得られます。

  -4   3  -2   1

次に、yieldsを使用して再コンパイルします。

18  14  17  15  16

これが戻り値になります。

再コンパイルではC、配列の最初の値であるを取得します。この場合18、、およびデルタを順番に適用します。そう18 + -4なります1414 + 3 gives 17など。

入出力

list / array / table / tuple / stack / etcが与えられます。任意の標準入力メソッドを介した入力としての符号付き整数

上記のデルタ反転方法に従って、変更可能なデータを受け入れ可能な形式でもう一度出力する必要があります。

0 < N < 10各数値が範囲内にあるN個の入力を受け取ります-1000 < X < 1000

テストケース

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

ノート

  • 上記で述べたように、少なくとも1つ、9つ以下の入力を常に受け​​取ります。
  • 出力の最初と最後の番号は、常に入力の番号と一致します。
  • 標準入出力のみが受け入れられます
  • 標準的な抜け穴が適用されます
  • これはなので、最小のバイト数が勝ちです!
  • 楽しむ!

そして勝者は...

デニス!誰が最初に1位になり、それから短い解決策で自分を打ち負かし、1位と2位の両方を獲得しました!

彼らのゼリーとのais523への名誉ある言及は、デニスが彼らの直前に入らなかった場合、2位になったことでしょう。


1
これらのデルタの課題は、数学で不要なデルタがどれだけあるかを証明しただけです。
アタコ16

4
数学で不要なデルタがどのように存在するか数学の最も重要な分岐の1つは、(無限に小さい)デルタに
ルイスメンドー

1
私はまだ幸せではありません幸せです
ATaco

私はできませんC ppcgに数学的な挑戦を...:P
Mukulクマール

回答:


9

ゼリー、5バイト

.ịS_Ṛ

これは、Glen OのJulia answerのアルゴリズムを使用しています。

オンラインでお試しください!

使い方

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

7
デニスプリーズ
ファンドモニカの訴訟

12

ゼリー、6バイト

I;ḢṚ+\

オンラインでお試しください!

使い方

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.

7
デニスください
ATaco

あなたは数分で私を打ったように見えます。驚くべきことに、私たちのプログラムはまったく同じではありません(私が持っている場所がありますU)。それが重複を考慮しないほどそれらを十分に異なるものにするかどうかはわかりません。

@ ais523はUベクトル化を行いますが、フラット配列に対する動作は同じです。
デニス

4
私は自分の答えを削除すると思います(自分で「正しい」答えを思いついたので少しイライラしながら、ここでの唯一の本当の問題は他の誰かが最初に同じ答えを見つけることができたということです) 。

どのASCII形式で6バイトとして出力されますか?XubuntuのPlumaは10バイトであり、Julia は0x1e22および0x1e5aとして保存するため、それぞれ3バイトが必要です。
グレンO

8

ジュリア、24バイト

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

これが問題を解決する「賢い」方法です。配列の負の反転では「デルタ」が反転しているので、間違った場所で開始/終了するという事実を修正する必要があります。


6

スノーマン 1.0.2、72バイト

((}#0AaGwR#`wRaCaZ`0NdE`aN0AaG:dU,0aA|1aA,nS;aM`0wRaC|#0aA*|:#nA*#;aM*))

オンラインでお試しください!

これは、現在のパーマバーとの間で入力および出力を行うサブルーチンです。

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

6

JavaScript(ES6)、45 37バイト

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

@JHMのMathematicaの答えのポート。(私はそれを自分で導出できたと確信していますが、現時点ではそうではありません。)編集:@ edc65のおかげで8バイトを節約しました。


あなたが必要[...とする理由はあります]か?
ママファンロール

1
@MamaFunRollそれ以外の場合は変更されますa。これはプログラムの後半で使用されます
コナーオブライエン

そうそう、忘れてしまった:P
ママファンロール

37:a=>a.reverse(z=a[0]).map(e=>z+a[0]-e)
edc65 16

@ edc65ああ、昨夜は十分に目を覚ましz=a[0]ていましたが、[...]and を削除するのを忘れました(,i,b)
ニール

4

Mathematica、23バイト

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

名前のない機能。結果は単純です:reverse((最初の要素)+(最後の要素)-(各要素))。


4

Python 2、96 74 54 44バイト

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

入力は、角括弧で囲まれた配列として与えられます。出力は同じ形式です。

@Kadeに感謝します。これまでにやっていたことよりもはるかに簡単な方法を使用して22 42バイトを節約しました。

リスト内包からインデックスカウンターを削除して10バイトを節約してくれた@ Sherlock9に感謝します!

素晴らしい、今ゴルフをしていると、「取り消し線44はまだ44」の問題が発生します。; _;


何についてのlambda l:[l[0]+l[-1]-l[i]for i in range(len(l))][::-1]54バイトのために?:)(計算のためにグレンO.にクレジット)
ケード

ああ、どうして私はそれを理解しなかったのですか。ありがとう!:)
HyperNeutrino 16

アレックス、あなたは答えとしてそのラムダ関数を使用することができます:)
Kade

何。ああ。わかった、ありがとう!:)
HyperNeutrino 16

の代わりにl[i]for i in range(len(l))j for j in l14バイトを節約するために使用できます。
Sherlock9


3

R、37 30バイト

編集:今グレンOのジュリアの答えのアプローチを使用して

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

古い:

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

入力を読み取り、デルタを計算し、最初の要素と連結して累積合計を計算します。


2

MATL、8バイト

1)GdPhYs

オンラインでお試しください!

これは、定義の直接適用です。[18 19 17 20 16]例として入力を検討してください。

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]

異なるアプローチ、同じバイト数:

P_G5L)s+

試してみてください!

元の配列の最初と最後のエントリに加えて、反転および否定された配列。

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



1

아희(Aheui)、3 * 21文字+ 2 "\ n" = 65バイト

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

スタックinの入力を想定しています。出力はスタックstoredに保存されます。

このコードを試してみたい場合:

このコードの最初の行の最後に、文字の長さ(n)回を追加します(つまり、入力が7整数の場合、7回挿入します)。プロンプトごとに、1つの整数を入力します。

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

ここで試してみてください!(コードをコピーして貼り付けます)

のために1, 2, 3, 4, 5

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

し入力1234、及び5(5つのプロンプトが存在することになります)。

代替バージョン(65バイト)

빠쑥쌳터슉펴ㅇ삯씬희
뿌파파쎢싺솎
싺싹삭다뽀

65 bytes in UTF-8なんか言ってみませんか?
mbomb007 16

@ mbomb007。韓国語の文字がそれぞれ3バイトであることを知らない人もいます。
ジョンファンミン

1

C#42バイト

を取り、int[]を返しますIEnumerable<int>

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

(これは実際にはJHMのバージョンの移植版にすぎません。)


1

TSQL、200バイト

入力として使用されるテーブル変数

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

やってみて


1

PHP、60 56 52バイト

@ user59178のおかげで-4バイト

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

コマンドライン引数で動作し、アンダースコアをセパレータとして使用します。で実行
php -r '<code>' <space separated numbers>


1
$n制御変数として使用しない理由はありますか?私はそのようなバージョンを試してみましたが、4バイト短くなり、動作しているように見えました。
user59178 16

1

Perl 6の 48の33  30バイト

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

それを試してみてください

拡張:

{  # 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
      }
}

*-1またタイプWhateverCodeのラムダ式で*のみ位置パラメータです。


perlを話さない人への説明は?
チョイス

@Cyoce最短バージョン用に追加。これは、Perl 5を知っている人にも説明する必要があります。あなたが[\+]最初の例から疑問に思っていた場合、三角形を減らす[\+] 3,-1,1,-5(3,2,3,-2)[\,] 3,-1,1,-5((3,), (3,-1), (3,-1,1), (3,-1,1,-5))
Brad Gilbert b2gills



0

C ++ 14、103バイト

有するように、その入力を必要と名前ラムダ、としてrbeginrendback及びpush_back容器等vectordequeまたはlist

グレンOのジュリアの答えのアプローチを使用する

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

ゴルフをしないと使用法:

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



0

Clojure、101バイト

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

ほぼ説明に従います。

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

0

Java 7、96バイト

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

説明:

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

テストコード:

ここで試してみてください。

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

出力:

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

弊社のサイトを使用することにより、あなたは弊社のクッキーポリシーおよびプライバシーポリシーを読み、理解したものとみなされます。
Licensed under cc by-sa 3.0 with attribution required.