算术级数


11

您的任务是分析输入和输出第n个项(如果它是算术序列)的公式,否则应打印“ NAAP”。


输入值

输入(来自STDIN)将由几个数字组成,介于4到10个数字之间,其中每个数字的范围在-1000到1000之间(包括-),并以定界符(空格,逗号或分号[您的偏好])。这是一些示例输入。

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”(“不是算术级数”的缩写)。

如果算术级数,则程序应将序列的简化的第n个项打印到STDOUT。

例:

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

说明:这是一个AP,因为存在一个共同的区别($ 3-1-2 $)。然后使用公式$ a(n)= a(1)+(n-1)d $

一种ñ=一种1个+ñ-1个d

一种ñ=1个+ñ-1个2

一种ñ=1个+2ñ-2

一种ñ=2ñ-1个

因此输出为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

这是因此以字节为单位的最短代码胜出!(对不起,数学jax)

欢迎任何建议!


4
您可能应该将自己的帖子在沙盒中保留一个多小时……
Mego 2015年

3
一小时真的很短。并非每个人都在不断检查沙箱。24小时为佳。
Mego 2015年

8
抱歉,尽管MathJax可在Meta上运行,但在主要的PPCG网站上却无法使用...
ETHproductions 2015年

1
您应该以递减的顺序添加测试用例。
lirtosiast 2015年

2
0,0,0,03,1,-1,-3,-5算术级数?如果是这样,我认为它们将是很好的测试用例,因为它们破坏了我正在尝试的方法。
xnor

Answers:


5

Pyth,30个字节

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

测试套件

要检查它是否为算术行列,将在每个元素和前一个元素之间使用向量减法-VtQQ。三元数检查结果(?tJ{)中是否有多个值,如果有则打印NAAP。然后,为了获得正确+-正确的结果,将使用mod格式%+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(如果级数是算术运算,则会在图形屏幕()上使用输出,该输出会自动将参数连接在一起。

假定使用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

Matlab,103个字节

x=str2num(input('','s'));y=diff(x);if range(y) disp('NAAP'),else fprintf('%gn%+g\n',y(1),x(1)-y(1)),end

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

通常,您将使用lambda表达式形式之一,以便删除sub f。另外,如果您使用@_而不是则@a可以节省几个字节。{my@b=@_.rotor...。同样,您不应该在if语句的条件周围加上括号,这不是Perl5。如果将其更改if@b.end&&"NAAP"||$_=...您可以节省更多的字节。if如果"@b[0]n{'+'x($_>=0)}$_"改用了最后一条语句,则也可以省掉4个字节。
布拉德·吉尔伯特b2gills 2015年

sub一开始就不需要,否则它会成为一个匿名块。也只是让你知道,我不会想到利用.map({[-] $_})我会使用可能».map(*-*).flat是更长的时间,现在我必须去通过我自己的记录,看看我能与你的绝招缩短。
布拉德·吉尔伯特b2gills

1

Ruby,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

By using our site, you acknowledge that you have read and understand our Cookie Policy and Privacy Policy.
Licensed under cc by-sa 3.0 with attribution required.