양의 정수의 합. [닫은]


14

문제:

정수 세트가 주어지면 모든 양의 정수의 합을 찾으십시오.

입력:

  • t – 테스트 사례 수 [ t <1000]
  • 다음 t 행 각각 에서 정수 N [-1000 ≤ N ≤ 1000]

산출

프로그램은 모든 양의 정수의 합을 출력해야합니다.

온라인 판사에서 코드 확인

점수

점수는 ASCII 코드 ≤ 32 인 기호를 제외하고 프로그램의 소스 코드 크기와 같습니다.

최고 점수 목록은 다음과 같습니다. Python 최고 점수 (최고 점수는 29)


13
spoj.pl/SHORTEN에는 훨씬 더 많은 코드 골프 문제가 있습니다 . 그래도 여기서 복제하는 요점을 보지 마십시오.
hallvabo

3
이 질문에 python 태그가 붙은 이유는 무엇입니까? python solution에만 관심이 있습니까?
Aman ZeeK Verma

24
컨테스트 사이트의 질문이 여기에 게시되지 않아야한다고 생각합니다.
fR0DDY

2
나는 이미 SPOJ에서 이것을했습니다. 얼마 전에 그들은 파이썬 3에서 모든 파이썬 2.6 답변을 홍보했습니다. 그중 일부는 파이썬 3에서 실행되지 않고 파이썬 3에서는 더 길어질 것입니다. 인쇄 x. 그래서 나는 더 이상 SPOJ를 진지하게 생각하지 않습니다. 나는 Tim Peters와 묶여 있고 그것은 저에게 충분합니다 :)
gnibbler

4
T테스트 케이스에 T숫자 다음에 추가 데이터가 포함되어 있기 때문에 (number of ... errr ... numbers (?)) 를 건너 뛰는 것은 옵션이 아니라는 점 을 지적하고 싶습니다. 코드는 SPOJ에서 실패합니다. 모든 사람 (아래 3 답변)은 똑똑하게 첫 번째 정수를 건너 뛰는 것처럼 보였습니다.
st0le

답변:


34

공백, 0

나는 저항 할 수 없었다. S= 공백, T= 탭, N= 개행, 모두 ASCII 코드 <= 32가 있습니다.

SSSSNSSSSNTTSSSSSTNTNTTNSSSNSSSSTNTTTNTSTNSSSSTNSSSSTNTTTSSSSTNTSSTTTSSSSSTSNTNTTSSSSTSNTTTNTTSNSSSSNSSSSTSNTTTSSSSNTTTTSSSTTSNSNSNNSSTNSSSSNTTTTNSTSSSSTSTSNTNSSNNN

간편한 복사 및 붙여 넣기를 위해 Base64로 인코딩되었습니다.

ICAgIAogICAgCgkJICAgICAJCgkKCQkKICAgCiAgICAJCgkJCQoJIAkKICAgIAkKICAgIAkKCQkJ
ICAgIAkKCSAgCQkJICAgICAJIAoJCgkJICAgIAkgCgkJCQoJCSAKICAgIAogICAgCSAKCQkJICAg
IAoJCQkJICAgCQkgCiAKIAoKICAJCiAgICAKCQkJCQogCSAgICAJIAkgCgkKICAKCgo=

3
(+1) 멋진 프로그램! 작은 "FWIW": S숫자의 이진 코딩에서 불필요한 9 개의 인스턴스로 인해 9 개의 문자를 제거 할 수 있습니다 . 이것들은 모두 폼의 푸시 투 스택 명령어 SSSS...N로, 4 번째 S코드는 불필요한 선행 0을 코딩합니다. (물론 이것은 점수에 영향을 미치지 않습니다.)
res

13

요소, 17 자 + 1 공백

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

이것이 처음으로 만들어진 언어입니다. 매우 컴팩트하고 사람이 읽을 수 있도록 설계되었습니다. 모든 명령어는 한 문자 길이이며 단일 기능을 수행합니다.

요소에는 두 개의 스택과 메모리 구조로 해시가 있습니다. 두 스택을 기본 스택과 제어 스택이라고합니다. 주요 스택은 산술, 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 --- 전 운영자 고양이

5
"사람이 읽을 수있는"의 의미를 이해하지 못한다고 생각합니다.
wchargin

3
@WChargin 그는 펄에
익숙해

@WChargin 모든 언어는 배우기 전까지는 읽을 수 없습니다. ;)
Martin Ender 2013

8

펄, 31

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

say이것을 사용하여 조금 더 짧게 만들지 않습니까? 29 자로 가장 잘 어울립니다.
Mr. Llama

아니요. say내장되어 있지 않으며 (적어도) 문자 수에 포함되는 명령 줄 스위치가 필요 하기 때문 입니다.
Timwi

$\ 대신 다음을 사용하여 29 바이트로 단축 할 수 있습니다 $i.<>;$\+=$_*($_>0)while<>;print
Heiko Oberdiek

5

루비 1.9.2, 37

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

루비 스크립트 이름 file_with_ints처럼 호출하십시오.


루비를 많이 읽을 수는 없지만 테스트 사례 수를 읽습니까?
Joey

아니 그것은 ...
st0le

@ st0le : 방금 현재 솔루션을 해결하는 솔루션이 없음을 알았습니다.
Joey


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

4

펄, 33

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

공간이 필요하지만 계산하지 않는 것이 이상해 보입니다. 아, 규칙은 규칙입니다.

흠. 아마도 총계에 포함되지 않는 변수 이름을 사용하여 벗어날 수 있습니다. 문제는 코드를 어떻게 붙여 넣을 지 잘 모르겠습니다.


그것들을 $ ^ A-$ ^ Z로 보여주십시오. 그러나 많은 변수들은 특별한 의미를 가지고 있습니다.
ninjalj

3

클로저, 71

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

이것은 어떤 출력을 생성하고 있기 때문에 실패하지 않는 *in*하지 않은 것입니다 java.io.BufferedReader의 요구에 따라 line-seq.
John Cromartie

또한 라인 입력 수 t를 무시합니다 .
John Cromartie

3

기억에 남는 데니스 엠 리치

유닉스 57¹ 72 :

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

i가 ints를 포함하는 파일이라고 가정합니다.

¹)이 잘못되어 행 수를 포함했으며 1 행이 너무 적었습니다.

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


2

하스켈, 51

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

(명확하지 않은 추가 공간은 계산에 포함되지 않기 때문에)

Haskell은 흥미 롭습니다. 많은 공간이 필요한 프로그램을 얻는 경향이 있기 때문입니다.


2
을 잊었습니다 filter (>0).
FUZxxl

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
다음 번에 원래 답변을 편집하십시오
ratchet freak

제 (제거 return 0;) 및 ( {}위해를 for)
l0n3sh4rk

b,x="%d";main(a,t){for(scanf(x,&t);t--&&scanf(x,&a);)b+=(a>0)*a;printf(x,b);}<-77 바이트
walpen

@walpen : 그들은 매개 변수와 같은 "argc"가 1로 설정되었다는 사실을 사용했습니다. 당신의 b는 초기화되지 않았습니다 ...
VX

2

베 펀지 -98 (24)

(음수를 읽을 수있는 인터프리터를 사용하십시오 (약간의 일반적인 버그로 보이지만 RcFunge은 작동합니다))

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

펄 (25)

(Perl은 변수 이름의 제어 문자를 허용하며, 변수 ^ B (ASCII 2)라는 이름을 지정하여 목표에 포함되지 않습니다.)

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

(일반 변형 (27 자)) :

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

변수 이름을 보았을 때 펄 답변을 먼저 무시하고 그 아래에있는 훌륭한 이름을 완전히 놓쳤습니다.
ardnew

2

APL (10)

+/{0⌈⎕}¨⍳⎕

설명:

  • ⍳⎕: 행을 읽고 사용자 입력 N에 대한 목록 [1..N]을 제공합니다.
  • ¨:이 목록의 각 요소에 대해 ... (즉, N 번 수행)
  • 0⌈⎕: 줄을 읽고 최대 0을 입력하고 N을 입력하십시오.
  • 이제 사용자가 입력 한 모든 양수 N과 사용자가 음수를 입력 한 0의 목록이 있습니다.
  • +/ 이 목록의 합계를 제공합니다.
  • 결과는 기본적으로 출력됩니다 (우리는 다른 작업을 수행하지 않기 때문에).

2

매스 매 티카 : 18 16

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

멋진 기능이지만 어떻게 이것이 줄 바꿈으로 지정된 입력을 처리합니까? 테스트 케이스 수 매개 변수 t를 합계의 일부로 어떻게 통합하지 않습니까? 더 많은 것이 주어 지더라도 지정된 테스트 사례 수까지만 어떻게 합됩니까?
Jonathan Van Matre

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$.@

마리 누스의 답변을 보면서 약간의 영감을 얻어 24 자까지 관리했습니다. 그러나 나는 완전히 다른 접근법을 가지고 있습니다.


1

PYTHON 2.x, 50 자

r=input
print sum(i for i in (r() for j in range(r())) if i>0)

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

클로저, 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

펄, 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
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.