算数の進行


11

あなたの仕事は、入力を分析し、それが算術シーケンスである場合、n番目の項の数式を出力することです。


入力

入力(STDINから)は、区切り文字(スペース、コンマ、またはセミコロン[いずれかあなたの好み])。入力例を次に示します。

12,14,16,18       //valid
-3 4 5 1 -2 -4    //valid
45;35;-35         //invalid (only three numbers are present instead of the minimum of 4 numbers)
2,32;21,321       //invalid (it uses two different delimiters: `,` and `;`)

出力

プログラムは、最初に入力が算術級数であるかどうかを確認する必要があります。

算術進行(AP)の概要:すべてのAPには共通の違いがあります。これは、$ n $と$ {n-1} $番目の用語の違いです(基本的には$ a(n + 1)a-a (n)$ はシーケンスの関数です)。この違いは、APの$ n $の値に対して同じままです。共通の違いがない場合、算術シーケンスではありません。n番目の項の値を計算するには、次の式を使用します$ a(n)= a(1)+(n-1)d $ここで、$ a(1)$は最初の項で、$ d $は共通です差。

算術級数でない場合、プログラムはエラーメッセージ「NAAP」(「Not An Arithmetic Progression」の略)を出力する必要があります。

それは場合等差数列、プログラムはSTDOUTにシーケンスの簡略n番目の用語を印刷しなければなりません。

例:

> 1,3,5,7,9
2n-1

説明:これは、一般的な違い($ 3-1 = 2 $)があるためAPです。次に、式$ a(n)= a(1)+(n-1)d $を使用します

an=a1+n1d

an=1+n12

an=1+2n2

an=2n1

したがって、出力は2n-1(スペースがないことに注意してください)


デフォルトでは、標準の抜け穴は許可されていません。

必要に応じて、関数を作成できます(パラメーターとして数値の配列を使用)。そうでない場合は、入力を文字列または配列として受け取り、それに応じて出力する完全なプログラムを作成する必要があります。

テストケース:

1。

1,3,5,7,9
2n-1

2。

1 3 12312 7 9
NAAP

3。

-6;8;22;36;50
14n-20

4。

5,1,-3,-7,-11,-15
-4n+9

5。

-5,-7,-9,-11,-13,-15
-2n-3

6。

3,3,3,3,3,3,3,3,3
0n+3

7。

-4,-5,-6,-7
-1n-3

これはので、バイト単位の最短コードが勝ちです!(悪いmath-jaxでごめんなさい)

どんな提案でも大歓迎です!


4
おそらく... 1時間以上サンドボックスであなたのポストを維持する必要があります
MEGO

3
1時間は本当に短い時間です。誰もが常にサンドボックスをチェックするわけではありません。最低でも24時間です。
MEGO

8
申し訳ありませんが、MathJaxはMetaで動作しますが、メインのPPCGサイトでは動作しません...
ETHproductions

1
シーケンスを減らすテストケースを追加する必要があります。
リルトシアスト

2
ある0,0,0,03,1,-1,-3,-5等差数列?もしそうなら、彼らは私がしようとしていた方法を破ったので、彼らは良いテストケースになると思います。
XNOR

回答:


5

Pyth、30バイト

?tJ{-VtQQ"NAAP"+hJ%"n%+d"-hQhJ

テストスイート

算術行列であるかどうかを確認するために、各要素と前の要素の間でベクトル化された減算を使用します-VtQQ。3進法は、結果に複数の値があるかどうかをチェックし(?tJ{)、あるNAAP場合は出力します。次に、+またはを取得するため-に、mod-formating %+dが使用されます。


3

Haskell、103バイト

z=(tail>>=).zipWith
f l@(a:b:_:_:_)|and$z(==)$z(-)l=show(b-a)++'n':['+'|b-a<=a]++show(a+a-b)
f _="NAAP"

使用例:

f [-6,8,22,36,50]   ->   "14n-20"
f [60,70,80,90]     ->   "10n+50"
f [2,3,4,6,7,8]     ->   "NAAP"

Haskellの場合と同様、派手な出力フォーマット(たとえば、数字と文字列の混合)は大量のバイトを消費します(約40)。プログラムロジックは非常にコンパクトです。

f l@(a:b:_:_:_)           -- pattern match an input list with at least 4 elements,
                          -- call the whole list l, the first two elements a and b
z=(tail>>=).zipWith       -- the helper function z takes a function f and a list l
                          -- and applies f element wise to the tail of l and l

           z(-)l          -- make a list of neighbor differences
     z(==)                -- then compare these differences for equality
 and                      -- and see if only True values occur

       show ...           -- if so format output string

f _="NAAP"                -- in all other cases ( < 4 elements or False values)
                          -- return "NAAP"

2

TI-BASIC、70バイト

Input X
ΔList(∟X->Y
If variance(Ans
Then
∟X(1)-min(Ans
Text(0,0,min(∟Y),"n",sub("+-",(Ans<0)+1,1),abs(Ans
Else
"NAAP

TI-BASICの数値から文字列への変換の欠如を改善するために、これはText(、進行が算術である場合にグラフ画面()の出力を使用します。

これは、2進数のマイナス記号ではなく、TI-BASICの高マイナス文字(少し似ている)を使用して負の数値が入力されることを前提としています。ただし、出力ではバイナリのマイナス記号が使用されます。


2

Japt60 52 51バイト

V=N¤£X-NgY+1};W=Vg;Ve_¥W} ?W+'n+'+sU<W +(U-W :"NAAP

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

インタプリタがどのように設計されているかであるため、入力は任意のセパレータで指定できます;)

非ゴルフと説明

V=N¤  £    X-NgY+1};W=Vg;Ve_  ¥ W} ?W+'n+'+sU<W +(U-W :"NAAP
V=Ns2 mXYZ{X-NgY+1};W=Vg;VeZ{Z==W} ?W+'n+'+sU<W +(U-W :"NAAP

            // Implicit: N = list of inputs, U = first input
V=Ns2       // Set variable V to N, with the first 2 items sliced off,
mXYZ{       // with each item X and index Y mapped to:
X-NgY+1}    //  X minus the item at index Y+1 in N.
            // This results in a list of the differences (but the first item is NaN).
W=Vg;       // Set W to the first item in V (the multiplication part).
VeZ{Z==W}   // Check if every item in V is equal to W.
?W+'n+      // If true, return W + "n" +
'+sU<W      //  "+".slice(U<W) (this is "+" if U >= W, and "" otherwise)
+(U-W       //  + (U minus W [the addition part]).
:"NAAP      // Otherwise, return "NAAP".
            // Implicit: output last expression


1

CJam、38バイト

{:T2ew::-):U-"NAAP"UW*"n%+d"T0=U+e%+?}

これは、スタック上の配列を入力として受け取り、スタック上の文字列を出力として残す匿名関数です。テスト用に追加のI / Oコードでオンライン試してください

説明:

:T      Save a copy of input in variable T for output generation.
2ew     Generate list of pairs of sequential elements.
::-     Reduce all pairs with subtraction operator.
)       Pop last value from list of differences.
:U      Save difference value in variable U for output generation.
-       Set difference. This will leave an empty list (falsy) if all values are the same.
"NAAP"  First value for ternary operator, for case where not all values are the same.
UW*     Start generating output for success case. Need to flip sign of difference saved
        in variable U, since it was 1st value minus 2nd, and we need the opposite.
"n%+d"  Push format string for printf operator. The + sign in the format specifies that
        the sign is always generated, saving us from needing different cases for the
        value being negative or positive.
T0=     Extract first value from original input saved in variable T.
U+      Add the difference (with the "wrong" sign) to it.
e%      "printf" operator.
+       Concatenate two parts of result.
?       Ternary operator for picking one of the two output cases.

1

JavaScript(ES6)、91バイト

x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

説明

x=>(
  s=x.split`,`,       // s = array of input numbers
  m=s[1]-s[0],        // m = the multiplication part of the formula
  a=s[0]-m,           // a = the addition part of the formula
  s.some((n,i)=>      // check if the rest of the numbers follow this sequence
    n!=m*i+m+a
  )?"NAAP":
  m+"n"+(a<0?a:"+"+a) // output the formula
)

テスト

<input type="text" id="input" value="5,1,-3,-7,-11,-15" /><button onclick='result.innerHTML=(

x=>(s=x.split`,`,m=s[1]-s[0],a=s[0]-m,s.some((n,i)=>n!=m*i+m+a)?"NAAP":m+"n"+(a<0?a:"+"+a))

)(input.value)'>Go</button><pre id="result"></pre>


1

Perl 6、123 102 101バイト

編集:違いを否定しないでください

編集:匿名サブ、論理演算子、および文字列補間を使用します。ありがとう、ブラッド・ギルバートb2gills

sub{my@b=@_.rotor(2=>-1).map({[-] $_}).squish;$_=@_[0]+@b[0];@b.end&&"NAAP"||"@b[0]n{'+'x($_>=0)}$_"}

テストプログラム(stdinから読み取り):

my $f = <the code above>
$f(split(/<[;,]>/, slurp)).say

説明:

my @b =
  @_.rotor(2=>-1)  # sliding window of 2: (1,2,3,4) => ((1,2),(2,3),(3,4))
  .map({[-] $_})  # calculate difference (subtract all elements and negate)
  .squish;         # remove adjacent elements that are equal

@b.end        # @b.end is last index, @b.end = 0 means @b has only 1 element
&& "NAAP"     # true branch
|| "@b[0]n{'+'x($_>=0)}$_" # string for an+b, 
        # {'+'x($_>=0)} inserts a plus sign using the repetition operator x

通常、ラムダ式形式のいずれかを使用して、sub f。また、@_代わりに使用@aすると、数バイト節約できます。{my@b=@_.rotor...。また、if文の条件の周りに括弧を置かないでください。これはPerl 5ではありません。それを変更するif@b.end&&"NAAP"||$_=...、さらに数バイト節約できます。代わりにif使用した場合は、最後のステートメントを廃止して"@b[0]n{'+'x($_>=0)}$_"、4バイト節約することもできます。
ブラッドギルバートb2gills

sub最初は必要ありませんが、それなしでは匿名ブロックになります。また、あなたが知っているように、私は.map({[-] $_})おそらく».map(*-*).flatより長いものを使用することを考えていませんでした、今私はあなたのトリックでそれを短くできるかどうかを確認するために自分のエントリを調べなければなりません。
ブラッドギルバートb2gills

1

ルビー、95 78 76バイト

->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}

78バイト

->s{puts s.reduce(:+)==s.size*(s[-1]+i=s[0])/2?"%dn%+d"%[v=s[1]-i,i-v]:"NAAP"}

95バイト

->s{puts s.reduce(:+)==s.size*(s[0]+s[-1])/2?"#{v=s[1]-s[0]}n#{"+"if (i=s[0]-v)>0}#{i}":"NAAP"}

ゴルフをしていない:

-> s {
  i,j=s
  puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"
}

使用法:

->s{i,j=s;puts s.reduce(:+)==s.size*(s[-1]+i)/2?"%dn%+d"%[v=j-i,i-v]:"NAAP"}[[-6,8,22,36,50]]

=> 14n-20

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