正整数之和。[关闭]


14

问题:

给定一组整数,找到其中的所有正整数之和。

输入:

  • t –测试用例数[ t <1000]
  • 在每个下一个的系,整数Ñ [-1000≤ Ñ ≤1000]

输出量

程序应输出所有正整数的和。

在在线裁判中检查您的代码

得分了

分数等于程序源代码的大小,但ASCII码≤32的符号除外。

以下是最佳成绩列表:Python最佳成绩(最高成绩为29)


13
有很多在更codegolf挑战spoj.pl/SHORTEN。但是看不到在此处复制它们的意义。
hallvabo

3
为什么将这个问题标记为python。我们仅对python解决方案感兴趣吗?
阿曼ZeeK Verma

24
我认为比赛网站的问题不应该在此处发布。
fR0DDY 2011年

2
我已经在SPOJ上做到了这一点。不久前,他们将所有Python2.6答案升级为Python3,即使其中一些不会在Python3下运行,并且在Python3中使用的时间更长-例如,必须使用int(input())代替input()和print(x)的x。因此,我不再非常重视SPOJ。我与蒂姆·彼得斯(Tim Peters)
息息相关

4
我只想指出,跳过T(... errr ... numbers(?)的数量)不是一种选择...因为测试用例在T数字之后包含额外的数据...您的代码将在SPOJ中失败。每个人(以下3个答案)似乎都巧妙地跳过了第一个整数。
st0le 2011年

Answers:


34

空格,0

我无法抗拒。S=空间,T =制表符,N=换行符,都具有ASCII码<= 32。

SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN

Base64编码,易于复制和粘贴。

ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ
ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg
IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo=

3
(+1)好程序!微小的“ FWIW”:由于9 S的数字二进制编码中不需要的实例,因此可以删除9个字符。这些形式的所有推号码到堆栈的指令SSSS...N,其中所述第四S代码的多余领先0。(当然这对分数没有影响。)
水库

13

元素,17个字符加1个空格

_'[_ 2:n;0>[n~+]]`

这是我的第一门建构语言。它被设计为非常紧凑且易于阅读。所有指令均为一个字符长,并且执行一个功能。

Element具有两个堆栈和一个哈希作为内存结构。这两个堆栈称为主堆栈和控制堆栈。主堆栈是进行算术,I / O和哈希操作的地方。控制堆栈是逻辑操作发生的地方,该堆栈控制while和for循环。

Element背后的基本思想是,有一个存储数字/字符串的哈希,而堆栈则用于对这些数字执行计算。然后,可以将这些计算的结果分配给哈希表中的某个位置,以备将来使用。哈希的不同内容称为元素,因此它类似于数组,但可以具有非数字名称。

编辑:您可以在这里找到Element(用Perl编写)的解释器。

这是运算符的列表:在某些示例中,m和n表示堆栈中已经存在的数字。

text  --pushes the string "text" onto the main stack
'     --pops from main stack and pushes onto control stack
"     --pops from control stack and pushes onto main stack
#     --pops from main stack and destroys
[]    --FOR statement (view the top number number from control stack and eval those many times)
{}    --WHILE (loop until top number on control stack is 0)
(     --pops from main stack, removes first character, pushes the remaining string onto stack, and pushes the removed character onto stack
)     --pops from main stack, removes last character, pushes the remaining string onto stack, and pushes the removed character onto stack
~     --pops from main stack, pushes contents of the element with that name
+-*/%^ --pops two most recently named elements, adds/negates/multiplies/divides/modulates/exponentiates them, and places the result on the stack
mn;   --pops m and n and assigns element n the value of m
mn@   --pops m and n and moves mth thing in stack to move to place n in stack
m$    --pops m and pushs size of m onto the stack
mn:   --pops m and n and pushes m onto the stack n times
mn.   --pops m and n and pushes m concatonated with n
m?    --pops m and pushes 0 onto control stack if m is '0' or and empty string, else pushes 1 
\     --escapes out of next character, so it isn't an operator and con be pushed onto the stack
><=   --pops two numbers off of stack and tests, pushes 1 onto control stack if true and 0 if false
`     --pops from main stack and prints
&|    --pops two items from control stack, performs and/or respectively, and pushes result back onto control stack
!     --pops a number off of control stack, pushes 1 if 0 or empty string, 0 otherwise
_     --inputs a word and pushes onto main stack
m,    --pops m from main stack, coverts it to char and pushes, converts to num and pushes
Newlines and spaces separate different elements to be pushed onto the stack individually, but can pushed onto the stack using \

这是该程序工作方式的演练:

_'[    --take the first line of input, transfer it to the control stack, and start a for loop
_ 2:   --take one more line of input, and duplicate it so that there are two copies
n;     --take one copy and put into element n
0>     --push a zero onto the stack, remove the zero and the other copy of the input, and compare. A 1 will be placed on the control stack if the input was greater than zero, a 0 otherwise.
[      --starts another for loop if the comparison was true. This loop will be repeated once if the comparison was true and no times if it was false, so it is the same as an IF statement.
n~     --pushes n onto the main stack, then pops it ans replaces it with the contents of n, which is the number stored earlier
+      --takes the number and adds it to the running total, which is contained as the last item on the stack
]      --ends the inner for loop
]      --ends the outer for loop
`      --print the top item (also the only item) on the stack to output

6
有了指向工作环境的指针,这样的条目将大为改善。
dmckee ---前主持人小猫,2012年

5
我认为您不理解“人类可读”的含义。
wchargin 2014年

3
@WChargin他习惯了Perl ...
Caridorc

@WChargin在您学习每种语言之前,每种语言都是不可读的。;)
Martin Ender's

8

Perl,31岁

<>;$i+=$_*($_>0)while<>;print$i

不会使用它say使它短一点吗?最适合29个字符。
拉玛先生先生2012年

不,因为say它不是内置的,并且(至少)需要一个命令行开关,该开关将计入字符数。
Timwi '04

它可通过使用被缩短到29个字节$\ ,而不是$i<>;$\+=$_*($_>0)while<>;print
的Heiko Oberdiek

5

Ruby 1.9.2、37

p eval [*$<].join.gsub(/\A\d+|-\d+|\n/, '+0')

像ruby脚本名file_with_ints一样调用。


我不能读很多Ruby,但是那还能读测试用例吗?
乔伊,

不,不是...
st0le 2011年

@ st0le:刚刚注意到,目前没有解决方案可以解决该任务。
乔伊,


5

哈斯克尔,58岁

仅对t整数正确地操作。尚未针对Spoj运行它,因为我只是不在乎在那儿​​注册。

f (x:l) = take x l
main = interact $ show . sum . f . map (max 0.read) . lines

什么是“ t整数”?
wchargin

4

C 89个字符的代码


x="%d";  main(b,a,t)  {  
  for(scanf(x,&t);t;t--)
    {  scanf(x,&a); a>0?b+=a:a; }  printf(x,b-1);
       return 0; }

我做了很多尝试,以减少我的代码少于63个字节,但是我只能将其减少到89个字节。请帮助我将其减少到63个字节或更少。


1)我数了90个字符。2)return 0;是不必要的,for可以将循环收缩为for(scanf(x,&t);t--;scanf(x,&a),a>0?b+=a:a);==,这会使78个字符...
VX

无法使用gcc 4.8.1进行编译error: initializer element is not computable at load time x="%d"
manav mn 2014年

4

Perl,33岁

<>;while(<>){$i+=$_ if$_>0}print$i

尽管空间是必需的,但不计算它似乎很奇怪。哦,规则就是规则。

嗯 我可能会避免使用一个也不计入总数的变量名。问题是,我不确定当时如何粘贴代码。


只需将它们显示为$ ^ A-$ ^ Z,但请注意,其中许多变量都有特殊含义。
ninjalj 2011年

3

Clojure,71岁

(reduce + (filter pos? (map #(Integer/parseInt %) (next (line-seq *in*)))))

这不会产生任何输出,并且会失败,因为*in*不是java.io.BufferedReader所要求的line-seq
John Cromartie 2013年

同样,它忽略了输入t的行数。
John Cromartie 2013年

3

纪念丹尼斯·里奇

UNIX 57¹ 72:

n=$(head -n1 i); echo $(($(head -n $((n+1)) i | tail -n $n | grep -v "-" | tr '\n' '+')0))

假设我是包含int的文件。

¹)是错误的,包括了行数,而又少添加了1行。

echo $(($(cat i | head -n $(head -n1 i)| grep -v“-” | tr'\ n''+')0))


2

Haskell,51岁

main = interact $ show . f . lines
f (x:l) = foldl (+) 0 $ map read l

(为清楚起见,请留出多余的空格,因为它们不算在内)

Haskell很有趣,因为您趋向于获得带有大量必要空间的程序。


2
你忘记了filter (>0)
FUZxxl 2011年

2

C,88


x="%d";  main(b,a,t)  {  
for(scanf(x,&t);t--;)  
{  scanf(x,&a); a>0?b+=a:0; }  printf(x,b-1);
return 0; }

再接再厉,代码减少了一个字符,请帮助我减少更多字符。


6
下次只需编辑原始答案
棘轮怪胎

删除(return 0;)和({}for for
l0n3sh4rk'4

b,x="%d";main(a,t){for(scanf(x,&t);t--&&scanf(x,&a);)b+=(a>0)*a;printf(x,b);}<-77个字节
walpen 2012年

@walpen:他们使用这样的事实,即他们的“ argc”参数参数设置为1,您的b未初始化...
VX

2

Befunge-98(24)

(确保您使用的解释器可以读取负数(似乎是一个常见错误,但是RcFunge可以工作))

<;-1\+*`0:&\_\#;.@;:;#&0 

佩尔(25)

(Perl允许使用变量名称中的控制字符,我将变量命名为^ B(ASCII 2),这样它就不会计入目标。)

<>; $ ^ B + = $ _ *!/-/ for <>;打印$ ^ B

(普通变体(27个字符)):

<>;$B+=$_*!/-/for<>;print$B

当我看到变量命名时,我首先忽略了您的perl答案,而完全错过了它下面的出色答案
ardnew

2

杀伤人员地雷(10)

+/{0⌈⎕}¨⍳⎕

说明:

  • ⍳⎕:读取一行,为用户输入N提供列表[1..N]
  • ¨:对于此列表中的每个元素...(即执行N次)
  • 0⌈⎕:读取一行,返回最大值0,然后输入N
  • 现在,我们有了一个列表,其中用户输入的所有正数均为N,用户输入负数的则为0。
  • +/ 给出此列表的总和。
  • 默认情况下输出结果(因为我们不对其进行任何其他处理)。

2

Mathematica:18 16

Boole[#>0]&/@x.x

不错的功能,但是它如何处理指定的换行符分隔的输入呢?它如何不将测试用例的数量参数t作为总和的一部分?即使给出了更多的测试用例,它如何只求和呢?
乔纳森·范·马特雷

1

PowerShell,44岁

($i=$input|%{+$_})[1..$i[0]]-gt0-join'+'|iex

1

Q,12

{0+/x(&)x>0}

样品用量

q){0+/x(&)x>0} 1 -1 2 3 -1
6

1

befunge,35 24

:0`j&1-\&:0`*+\:0`3*j$.@

通过看到marinus的答案,我得到了一些启发,我还管理了24个字符。但是我有一个完全不同的方法。



1

C,70 72个字符

s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",s?&i:&c);printf("%d",s-1);}

SPOJ网站上的结果绝对是不真实的-我不知道如何将其降低到63。

但是,通过滥用未定义的行为,在某些编译器上可以达到68个字符。以下内容在具有32位gcc的x86 Linux上有效,所有参数在堆栈上传递。

s;main(i,c){for(;c--;i>0?s+=i:0)scanf("%d",&i+!s);printf("%d",s-1);}

1

优秀,27

=SUM(INDIRECT("A2:A"&1+A1))

在A1中计数t,其余数据在a2中向下计数


1

Clojure,108岁

(let [[n & m] (->> *in* java.io.BufferedReader. line-seq (map read-string))]
  (->> m (take n) (filter pos?) (apply +) println))

我真的希望我能避免该java.io.BufferedReader.部分,因为它本身要花费24个字符。但是AFAIK没有它就无法从STDIN读取行。


1

Perl,20岁

I know it is old and trivial, but the Perl answer can be still improved:

#!perl -p
$.<2or$\+=$_*!/-/}{

This is awesome! But what does }{ mean/do?
daniero

0

C++:

#include<iostream>
using namespace std;
int main()
{
    int c,n,s=0;cin>>c;
    while(c--)
    {
        cin>>n;s+=n*(n>0);
    }
cout<<s;return 0;
}

115 characters long. Need to optimize it to 90. Any suggestions ?


2
Just the standard tricks: The return is unnecessary in standard C++ or C99, there is an implicit return 0 in main. By making the variables global you can drop the =0 initialization. Finally, for(;;) is the same number of characters as while() but you get two extra places to put an expression in.
han

This is already old, but also, writing std:: before cin and cout and getting rid of the using namespace std; can save 5 more characters.
Morwenn

0

PHP, 71

<?for($s=0,$t=fgets(STDIN)+0;$t--;$s+=($n=fgets(STDIN))>0?$n:0);echo$s;

0

Python: (92 characters)

t = int(raw_input())
n = [int(raw_input()) for i in range(t)]
print(sum([n[i] for i in range(t) if n[i]>0]))

Using a=raw_input and r=range and using a() and r() later can save quite a few characters.
Morwenn

0

scala 55 54:

println ((for (r <- 1 to readInt;
  i=readInt;
    if i>0) yield i)sum)

0

C

void main()
{
int n;
scanf("%d",&n);
for(int i=0;i<n;i++)
     {
     if(i>0)
     sum=sum+i;
     }
printf("sum of positive numbers is %d",sum);
}

1
Welcome to CodeGolf.SE! If you look at the other answer, you'll see that they have formatted code and a minimal header noting the implementation language; on more complicated challenges many also have notes on the implementation and any limits or surprises in the code. Without some of this, you answer is unlikely to be well received.
dmckee --- ex-moderator kitten

I counted the chars, added the indentation to make code-layout work, and removed the decoration of the output. Oh - now I have to count again. :)
user unknown

Added language name. There's a lot of room for reductions here - sum can be reduced to s, the output string can just be "%d", etc.
Gareth


0

45 chars in python

c=0
j=input
for i in j()*[0]:
    b=j()
    c+=b*(b>0)
print c

1
How you counted that? It gives me 54 characters.
manatwork

@manatwork, this question has non-standard scoring rules which don't count whitespace.
Peter Taylor

Oops, sorry. I missed that. Thanks, @PeterTaylor.
manatwork
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.