Notcalc (오답 계산)


33

골:

두 개의 자연수 (0부터 무한대까지의 정수)가 주어지면 해당 숫자의 합이 아니라 자연수 인 숫자를 출력합니다.

솔루션 예 (TI-Basic) :

  • A+B+1

  • not(A+B)

잘못된 해결책 :

  • A+B-1(입력의 0,0경우 -1자연스럽지 않은를 반환합니다 .)

  • "ABC"( ABC숫자가 아님)

노트:

  • 출력은 항상 두 자연수의 합이어야합니다 (실제로는 자연 수임)

  • -1, undefined, infinity, NaN및 오류 메시지는 자연수 없습니다. 우리의 목적 상 0당연합니다 (모든 수학자들이 동의하지는 않지만).


1
숫자를 문자열로 가져 와서 문자열로 출력 할 수 있습니까?
xnor

1
출력에 선행 0이있을 수 있습니까?
Kritixi Lithos

1
오버플로를 고려해야한다고 가정하므로 2 ^ 32 -1 및 2의 결과는 음수가 아니어야합니다.
adrianmp

1
쓸모없는 세부 사항에주의를 기울이기 때문에 작은 말 만하면됩니다 .0은 자연수가 아닙니다. 첫 번째 문장을 "음이 아닌 정수 두 개를 줘 ..."로 바꾸면 쓸만한 세부 사항이 남지 않습니다. :)
peech 2012

6
@peech 이것은 사실이 아닙니다. 일부 정의에서는 0이 자연수로 간주됩니다. 삭제되었으므로 볼 수 없지만이 문제에 대한 광범위한 대화가있었습니다.
밀 마법사

답변:


36

RProgN , 4 3 1 바이트

4가 여전히 4 인 경우 (;

E

가장 간단한 솔루션은 A와 B가 같은지 비교합니다. RProgN이 1이면 같으면 true를, 그렇지 않으면 0이면 false를 푸시합니다.

테스트 사례

0+0 = 1
1+0 = 0
0+1 = 0
1+1 = 1

온라인으로 사용해보십시오!


22
방금 교차 링크로 토끼 구멍을 내려갔습니다. 나는 평점 <S> 4 </ S> / 4
로한 Jhunjhunwala

2
@RohanJhunjhunwala 내 4를 잡아, 내가 간다
Albert Renshaw

4
4 <- U + 0336 (결합 문자)을 할 수있는 더 좋은 방법이 될 수있다
알버트 렌쇼

3
PSA : codegolf.stackexchange.com/questions/48100/… 원본이 사라졌습니다
Christopher

3
@AlbertRenshaw 이전 PPCG가 4a를 ​​넘어 섰습니까?
Rɪᴋᴇʀ

15

망막 , 3 바이트

 
1

온라인으로 사용해보십시오!

첫 번째 줄에는 줄 바꿈 앞에 공백이 있습니다. 스택 교환은 후행 공백을 잘 나타내지 않습니다.

입력은 10 진수로 표시되며 공백으로 구분됩니다 (예 :) 12 34. 이 프로그램은 공백을 a로 변경하여 1입력 숫자의 합이 되기에는 너무 큰 숫자를 만듭니다 (필수적으로 두 개 이상의 숫자가 있어야하며 두 숫자를 추가하면 1 자릿수보다 큰 숫자가 출력 됨) 더 큰 입력).


2
0 0작동해야합니다.
데니스

1
@ 데니스 : 나는 그것에 대해 궁금했다. 010기본적으로 모든 정수 파서를 통한 정수로 간주됩니다. 일부 정수 파서를 통해 유효하지 않은 8 진으로 간주 0 8되는 근거로 유효하지 않은 잠재적 인 주장을 볼 수 있습니다 018(다른 사람은 10 진수로 간주하지만). 이 프로그램은 입력 에서 선행 0 을 소수 로 취급하여 처리하는 것이 매우 기쁩니다 . 사람들이 문제를 보지 않고 다른 질문에 선행 0을 출력하는 프로그램을 작성했습니다. 주제에 관한 메타 게시물이 있습니까?

2
또는 . 1선행 0을 직접 반환하지 않으려는 경우.
Martin Ender 2012

@MartinEnder> 자연수
wizzwizz4

@ wizzwizz4 님을 팔로우하지 않습니다
Martin Ender 2012

15

파이썬 , 13 바이트

[(0,0)].count

온라인으로 사용해보십시오! 튜플로 입력을받습니다.

함수에 객체 메소드 를 사용 하면의 상용구를 피할 수 lambda있습니다.

lambda a,b:a-~b   # 15 bytes

여기서 아이디어는에 매핑 하고 그 밖의 모든 것을 매핑 (0,0)하는 1것입니다 0. 자연수 중 0+0합계 만 제공 하므로 0항상 합계와 일치하지 않습니다.

그늘이있는 부울을 출력 할 수 있다면 바이트를 다음과 같이 저장할 수 있습니다

(0,0).__ge__

이 검사 입력 튜플은 대부분에있는 경우 (0,0)에만 사실이다, (0,0). 파이썬에서 True==1그리고 False==0. 종료 코드를 통해 출력하고 Python Boolen으로 처리하면 2 바이트가 절약됩니다.

[(0,0)].pop

문자열 I / O가 허용되고 선행 0이 정상이면 8 바이트 솔루션이 있습니다.

'1'.join

이것은 a1b항상보다 큽니다 a+b.


1
int.__eq__10 바이트
블루

@ muddyfish 그래, 나는 suever의 대답도 보았고 평등을 사용하는 것을 생각하지 않았다. 그것은 bool을 반환하지만, 숫자 출력을 요구하는 도전에 iffy라고 생각합니다.
xnor

1
IMO 숫자처럼 헤엄 치고 숫자처럼 떨면 숫자라고 가정하는 것이 합리적입니다.
CalculatorFeline

13

MATL 등 1 바이트

=

두 개의 자연수를 입력으로 받아 들여 비교합니다. 같으면 출력은 1같고 같지 않으면 출력은 0입니다. 이것은 @ATaco 솔루션과 동일한 접근 방식입니다.


3
=솔루션은 Jelly에서 1 바이트 동안 작동합니다. 나는 사소한 해결책에 대한 별도의 답변을 만들 가치가 없기 때문에 의견에 언급 할 것이라고 생각했습니다.

@ ais523이를 포함하도록 업데이트되었습니다. 감사.
Suever


APL과 J를 추가 할 수 있습니까?
Adám

@ Adám 물론입니다. 내가 연결할 수있는 TIO 링크가 있습니까?
Suever

10

자바 스크립트, 10 바이트

x=>y=>!x+y

다음과 같이 카레 구문을 사용하여 2 개의 숫자를 사용합니다.

(x=>y=>!x+y)(0)(0) // 1

4
사이트에 오신 것을 환영합니다! :)
DJMcMayhem

고마워 =) 나는 한동안 도전을 읽고 있었고, 시작하기 좋은 곳을 찾으려고 노력했다.
Malivil

9

Vim, 3 바이트 / 키 스트로크

<C-a>gJ

온라인으로 사용해보십시오!

참고 <C-a>실제로 CTRL-A 바이트를 나타냅니다 0x01.

나는 프로그래밍 언어가 아닌 vim이 골프 언어와 경쟁 할 수있을 때 그것을 좋아합니다. :) 입력은 다음 형식으로 제공됩니다.

a
b

이것은 단순히 첫 번째 숫자를 하나씩 증가시키고 (이것이 <C-a>부분 임) 두 숫자의 문자열 표현을 결합합니다. 내가 알 수있는 한, 이것은 결코 합계를 초래해서는 안됩니다.


9

Brain-Flak , 8 바이트

({}{}())

온라인으로 사용해보십시오!

이것은 내가 작성한 것 중 가장 읽기 쉬운 뇌-답변입니다. :)

설명:

(      )    # Push the sum of all the following:
 {}         #   The first input
   {}       #   The second input
     ()     #   and one

대체 솔루션 (또한 8 바이트) :

({}[]{})    # Sum + 1
([]{}{})    # Sum + 2

양수로만 작동하는 다른 솔루션이 많이 있습니다.

(<{}>{})
({}<{}>)
({{}}())
({{}()})
({{}}[])
({{}[]})


6

TI 기본, 3 바이트

not(max(Ans

대체 솔루션 :

10^(sum(Ans         3 bytes @DestructibleWatermelon
not(sum(Ans         3 bytes
1+sum(Ans           4 bytes
Input :X=Y          5 bytes @ATaco
Input :X+not(Y      6 bytes
Input :not(X+Y      6 bytes
Input :10^(X+Y      6 bytes
Input :X+Y+1        7 bytes
Input :not(max(X,Y  7 bytes
Ans(1)=Ans(2        8 bytes
Ans(1)+not(Ans(2    9 bytes
not(Ans(1)+Ans(2    9 bytes

TI-Basic에서 질문의 예를 작성했다는 것이 흥미롭지 만 더 짧은 것을 잊었습니다. A=B (또는 어쩌면 알아 우리에게인가?)


1
OP가 질문에 초단파 솔루션을 게시 할 때 아무도 그것을 좋아하지 않아 이길 수 없습니다.
mbomb007

@ mbomb007 나는 생각했지만, 그것은 단지 스 니펫 일 뿐이며 전체 프로그램이 아닙니다. Prompt A,B:그것들에 추가 하면 바이트 수가 각각 8 바이트가됩니다.
Timtech 2012

1
@Timtech 정확하게. 예를 들어 좋은 대답을하고 싶지 않고 단지 예를 원했습니다.
Julian Lachniet

@JulianLachniet 나는 이해하고 감사합니다 :)
Timtech

6

근접 , 2 바이트

+<

온라인으로 사용해보십시오!

설명

+     The sum of the elements in the Input...
 <    ...is strictly less than the Output
      (implicitely label the output with an integer respecting this constraint)

이 경우 항상으로 표시 A+B+1됩니다 Input = [A, B].


5

Mathematica, 5 바이트

1+##&

두 인수의 합에 1을 더한 값을 출력합니다. 예를 들어 1+##&[2,5]yields 8입니다.

(사이드 노트 : Binomial하지만 거의 작동 Binomial[1,0]=1하고 Binomial[4,2]=6반례이다, 나는 비록 그들이 유일한 반례을 것 같아요.)


Pochhammer보다 더 나은 것 같습니다 Binomial. 내가 알 수있는 한 1,0실패합니다.
Martin Ender 2012

아, KroneckerDelta모든 입력에 대해 작동합니다 (일부 esolang의 동등 검사와 동일 함). 실제로는 다시 구현하는 Boole[#==#2]&것이 더 짧지 만 그대로 작동하는 내장 기능을 찾고 있다고 가정합니다.
Martin Ender 2012

5

PHP, 17 바이트

<?=1-join($argv);

다음과 같이 실행하십시오.

echo '<?=1-join($argv);' | php -- 0 0
> 1

설명

이것은 단지 인수를 연결합니다. 첫 번째 인수 (스크립트 이름)는을 포함 -합니다. 따라서 음수로 표시되며 마이너스 부호로 부정합니다. 그런 다음 첫 번째 입력 번호가 0(0123 = 123) 인 경우를 대비하여 1을 추가 합니다.



4

Turtlèd , 12 바이트

매우 큰 숫자를 만듭니다

'1?:?:[1'0l]

온라인으로 사용해보십시오!

설명:

'1                write one on the starting grid square
  ?:?:            take a number, move right that many (repeat)
      [1   ]      while not on a grid square with a one on it
        '0l       put a zero on that square, move left
[implicit output of grid]

따라서 10 ** (x + y)를 출력합니다.



4

Java (OpenJDK 9), 10 bytes

a->b->a-~b

Try it online!


1
With currying, you can spare a byte: a->b->a-~b. Also works with Java 8, any edition (so there's no need to specify the OpenJDK 9)
Olivier Grégoire

@OlivierGrégoire Java has started to look like JS now >_>
Kritixi Lithos

@KritixiLithos Well... we had a hint this would happen for years: JavaScript ;-)
Olivier Grégoire

@KritixiLithos The specification for Java 9 has a section on 'ECMAScript 6 Compliance'.
Pavel

@ OlivierGrégoire 예, 그러나이 제출물은 자동으로 생성되므로 9가 추가되었습니다.
Pavel

4

허더, 40 bytes (non-competing)

이것은 아마도 Hodor가 작성한 가장 짧은 프로그램 일 것입니다!

이것은 2 주간의 학교 휴가 동안 아무 것도 할 일이 없을 때 발생합니다. 절대적으로 아무 것도하지 않는 정말 쉽게 코딩 된 농담 언어를 만들어냅니다. 방학을 위해 예!

Walder
Hodor?!
Hodor?!
Hodor HODOR!
HODOR!!!

Walder Hodor의 원래 이름 이었으므로 프로그램을 시작하는 데 필요합니다.

Hodor?! STDIN 또는 단일 문자에서 숫자를 가져와 누산기를 입력으로 설정합니다.

Hodor 누산기에 1을 더하다

HODOR! 누산기를 숫자로 출력합니다.

HODOR!!!Hodor를 죽입니다! 안돼!

이것은 의사 코드입니다.

Take input
Take input
Add 1 to sum(inputs)
Output value

1
I think you need to come up with a different name for your language unless this is an interpreter of the pre-existing Hodor language created in 2015, which I'm fairly certain this isn't.
mbomb007

@mbomb007 No that isn't mine but there are languages with duplicate names. I know of two called 7 on this site (I just can't find them at the moment)
caird coinheringaahing

1
I'm pretty sure there's only one called 7, and it's this one. You could change the capitalization of the title for an easy fix, something like HODOR.
mbomb007

@mbomb007 mine is Hodor and theirs is hodor so that could be enough?
caird coinheringaahing

No, theirs has a capital H, as you can see from every time he uses the language name on his website.
mbomb007

3

SmileBASIC, 4 bytes

!A+B

not(A)+B
1+1=2 -> !1+1 -> 0+1=1
0+1=1 -> !0+1 -> 1+1=2


Out of curiosity, how does this support 2+1?
ATaco

2
2+1=3 -> !2+1 -> 0+1=1
12Me21

3

R, 13 bytes

sum(scan()+1)

Thanks to Jonathan Allan for his inputs !


@JonathanAllan : You're right, I changed my answer. Thanks !
Frédéric

OK, pretty sure 00 is the same as 0 though, maybe sep="1"?
Jonathan Allan

@JonathanAllan : damnit ! Thanks again !
Frédéric

Looking at the Tips For Golfing In R it seems scan() should be fine, accepting a vector input, like this. But we can do one byte better with cat(sum(scan()+1)). Maybe there is shorter?
Jonathan Allan

1
With the cat it is a full program, the alternative would be an unnamed function for the same byte cost function(a,b)a+b+1
Jonathan Allan

3

05AB1E, 1 byte

Q

Works the same as the RProgN answer.

Checks if a and b are the same. If so, print 1. Otherwise, print 0

Try it online!


3
¢ ( a.count(b) ) should also work for 1 byte.
Riley

@Riley you could post that as your own answer.
Okx

2
It's not different enough to needs it's own answer. I thought we could just combine both 1 byte solutions into one answer.
Riley

3

C 26 24 19 bytes

f(c,d){return!c+d;}

Ungolfed version:

int f(int c,int d)
{
   return !c+d; 
}

I hope I got the specification right. Can definitely be shortened!?

@Pavel Thanks for saving 2 bytes

@Neil Thanks for your input.


1
Do you need () around !c+d?
Pavel

@Pavel You're right, brackets were useless, updated!
Abel Tom

2
Not 100% sure but I think you can remove the space in your return, like return!c+d;
Metoniem

1
Lose the return and instead assign it with something like c+=!d
Ahemone

1
@AlbertRenshaw It's not something I'd rely on for portability but here are a couple of examples. I can't get it to work offline and it seems that it needs to be assigned to a non argument variable on TIO.. tio.run/nexus/…
Ahemone

3

MATLAB / Octave, 3 bytes

@eq

Accepts two inputs and checks for equality and yields 1 if they are equal and 0 otherwise.

Online Demo


4
Shouldn't this be @eq? That returns a function handle which can be used to evaluate to the desired function, while just eq is meaningless.
Sanchises

@Sanchises I've seen many answers go both ways: codegolf.stackexchange.com/questions/106149/compute-the-median/…. I'm not actually sure which is preferred.
Suever

Hmmm. I should think this is more like a snippet, while an @ turns it into a valid language construct. But maybe I'm just being pedantic.
Sanchises

3

brainfuck, 12 bytes

Simple solution that outputs A+B+1.

,>,[-<+>]<+.

Try it online


Alternate answer (12 bytes): ,>,[-<++>]<.
Julian Lachniet

@JulianLachniet will that output A+2B?
george

A+2B hacked when B=0
l4m2

@mbomb007 I'm saying the ,>,[-<++>]<. solution
l4m2

@JulianLachniet Yeah, that's not a valid answer because A+2B for input B=0, gives A.
mbomb007

3

dc, 5 bytes

?1n+n

Try it online!

Input: Two natural numbers separated by a space on stdin.

Output: The digit 1 immediately followed by the sum of the two numbers, which is a number larger than the sum of the two numbers.

Example:

Input: 222 333

Output: 1555


3

PHP, 13 bytes; (17 REPL-less)

!max($argv)+0

Examples

[0,0] -> 1
[0,1] -> 0
[1,0] -> 0

For those without REPL use

<?=!max($argv)+0;

and run using

echo '<?=!max($argv)+0;' | php -- 0 0

This answer is not valid because it doesn't output anything
aross

@aross If boolean cast was problem I updated my answer
mleko

Yes, you addressed both problems. The output would be true/false, not 1/0. Also, REPL :)
aross

3

Cubix, 9 8 bytes

u-~OII/@

Explanation

Expanded, this answer looks like this:

    u -
    ~ O
I I / @ . . . .
. . . . . . . .
    . .
    . .

The order of the instructions that are executed is II~-O@

II~-O@
I      # First input
   -   # Minus
 I~    # NOT(second input)
    O  # Output as integer
     @ # End program

Tested for all combinations of inputs where both are in the range 0-100.

Try it here.


3

APL - 4 Bytes

1++/

Takes array, sums its elements and adds one. Test:

 1++/1 2  
4
 1++/1 0
2


3

Hexagony, 7 bytes

?<.!?)@

Try it online!

Or in more readable format,

 ? <
. ! ?
 ) @

This beats the current Hexagony solution of 11 bytes.

Explanation:

If the first number is not 0, the program takes the following path:

Not 0

This reads the first number and branches right. Then it reads the second number, followed by wrapping and trying to read a third, but that doesn't exist so it reads 0. This is printed and the program terminated (note that if a>0, since b is non-negative a+b>0).

If the first number is 0, the program takes the following path to start with:

Is 0

This reads the first number and branches left. It hits the corner, taking the route from along the north-west edge because the number is 0, and reads the second number. It wraps, then increments the second number and prints.

Is still 0

It bounces against the <, printing the incremented second input again. It increments the value and takes the north-east edge again, but this time because the current edge a twice-incremented non-negative value which is definitely positive. It then tries to get a third input, but receives 0 instead.

Is still 0 some more

Finally it wraps and gets diverted by the arrow, then tries to read a fourth input and gets 0 again. It wraps and tries to read a fifth input and receives 0 for the last time. This it prints, and wraps to the @ and exits.

Note that b*(10^k+1)*10>0+b=b where k is the length of b in digits, so this works.


2

Billiards, 11 characters = 17 bytes

⇲
⇲
+
1
+
↥

Implements x + y + 1. Pretty elementary. It takes the inputs on two separate lines. (By the way, the language was modified slightly after the challenge, but only to suppress the prompt from inputting, not sure if this answer is still valid).

7 characters = 11 bytes, non-competing

This one is shorter but only possible after a new update of the language:

⇲
⇲
=
$

This uses x == y, which was shamelessly stolen from @ATaco's RProgN solution [ hope you don't mind (: ]. The $, on exit, outputs how many balls passed over it.


slightly after the language typo, also I think when the language had the input prompt, it would still be valid. I don't think output standards are that strict, and non-suppressible outputs are allowed I think
Destructible Lemon

@DestructibleWatermelon Oh, that was a weird typo. Thanks for the clarification. I actually modified the language, then came and saw the challenge, so I decided to add that note in there in case anyone decided to be picky about checking when the push was made to GitHub, but thank you for clarifying that.
HyperNeutrino
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.