뒤집힌 버전의 숫자를 반환


18

숫자가 계산기에 표시되면 해당 숫자의 다양한 변형이 어떻게 보이는지 고려할 수 있습니다. 예를 들어, 7 세그먼트 디스플레이에서 2는 다음과 같이 표시됩니다.

enter image description here

수평으로 뒤집 으면 다음과 같이 보입니다.

enter image description here

따라서 2의 미러 이미지는 5입니다.

이 과제의 과제는 한 자리 숫자를 가져 와서 거울 이미지 인 숫자를 반환하는 것입니다 (가능한 경우). 미러 이미지가 숫자처럼 보이지 않으면 가능한 경우 180도 회전 한 숫자를 반환하십시오. 둘 중 하나라도 해당되지 않으면 -1을 반환하십시오.

프로그램이 처리해야하는 전체 입력 및 출력 목록은 다음과 같습니다.

Input   Output
0       0
1       -1
2       5
3       -1
4       -1
5       2
6       9
7       -1
8       8
9       6

A와 도전, 가장 짧은 코드가 승리!


17
나는 당신의 마지막 요점에 동의하지 않습니다 – 7 세그먼트 디스플레이의 1은 단순히 다른쪽으로 뒤집 히므로 1은 1로
낮춰야

29
각 자리를 뒤집는 방법에 대해 혼란 스럽습니다. 2가 5가되면 6이 9가 아닌 9가 되야합니다. 그러나 6이 9가되면 뒤집기가 회전이므로 2가 5가 아닌 다른 2가됩니다.
kernigh

6
6, 9는 180도 회전하고, 2, 5는 수평으로 뒤집었고, 실제로 1, 3은 수직 축을 가로 지르는 반사입니다.
jimmy23013

22
질문에 정의 된 번역은 전혀 일치하지 않습니다. 왜 2와 5가 뒤집 히지 만 3은 뒤집 히지 않습니까?
Rynant 2016 년

4
전환 가능한 숫자에 대한 흥미로운 사실을 발견했습니다.이 숫자는 반대 이진 패턴을 형성합니다 (예 : 2 = 010, 5 = 101). 6 = 0110, 9 = 1001입니다. 누구나이 사실을 솔루션에 사용할 수 있습니까?
Jack Aidley

답변:


32

하스켈 -43 31

공상없는 43 자.

f 0=0
f 8=8
f 2=5
f 5=2
f 6=9
f 9=6
f _= -1

부분 기능으로 만들어서 31 자로 줄였습니다.

f=([0,-1,5,-1,-1,2,9,-1,8,6]!!)

4
나는 웃었다. +1하십시오.
seequ

6
+1 Haskell을 사용 하여 사양을 정확하게 수행 합니다 . 말한다!
recursion.ninja

1
난 당신이 필요하다고 생각하지 않습니다 f=유효한 표현으로 두 번째 솔루션
Cyoce

23

골프 스크립트, 15 14

스펙을 다시 읽고 입력이 문자열이어야한다는 것을 알았습니다.

"0.5..29.86"\?

실행하려면

echo -n 2 | ruby golfscript.rb a.gs

이전 버전 (정수 입력) :

[0.5..2 9.8 6]?

최신 (14 바이트)은 aditsuCJam 답변 에서 다소 영감을 얻었습니다 .


1
내가 그렇게 생각하지 않았다 믿을 수 없어 ...
Dennis


14

파이썬 2.x-28

'015..29.86'.find(`input()`)

2
구체적으로 파이썬 2.x.
seequ

6
Python 3을 사용하면 `s를 제거하고 2자를 저장할 수 있습니다.
Rynant 2016 년


8

CJam, 20 바이트

q25691347`"5296W"er~

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

산출

$ for i in {0..9}; { cjam <(echo 'q25691347`"5296W"er~') <<< $i; echo; }
0
-1
5
-1
-1
2
9
-1
8
6

작동 원리

q          " Read from STDIN. The leaves a string on the stack.            ";
25691347`  " Push the string '25691347'.                                   ";
"5296W"    " Push the string '5296W'.                                      ";
er         " Perform character transliteration.                            ";
~          " Evaluate the result. Examples: '2' returns 2, 'W' returns -1. ";

8

비 펀지 (93) - 18 14 20 바이트

Befunge가 2D 언어 줄 인 것은 다소 다르지만 주석 작성자가 옳다고 생각합니다. 그럼에도 불구하고이 순간에는 해설자가 옳습니다.

&1g01g-.  
! &  #* )'

단계 :

&

입력을 숫자 x로 읽어 스택에 밀어 넣습니다.

1g

위치 x, 1에서 문자 값 c ( '!'= 33 또는 '*'= 42. 빈 셀 = 32)를 가져옵니다.

01g-.

셀 0,1 (33)의 문자 값을 읽고 c에서 빼고 숫자 값으로 출력합니다.


2
아주 좋아요 +1하십시오.
seequ

길이를 수정하십시오 : 그것은 20 바이트의
HAR-wradim

1
실제로 바이트 수를 잘못 계산했습니다. 19 바이트를 사용했습니다 . 줄 바꿈과 공백을 계산합니다. 그러나 Befunge 98로 전환하면 하나를 저장할 수 있습니다. 1 행을 다음으로 변경 :&1g'!-.
Justin

8

자바-49

long f(int a){return(0x790a300601L>>(a*4)&15)-1;}

여기, 0x790a300601 원하는 출력으로 채워진 값이 있으며 양수로 만들기 위해 추가 된 값이 있습니다. 값은 값 내에서 니블로 저장되므로 값을 표시하려면 약간의 이동 및 마스킹이 필요합니다.

자바-100 (재미있는 옵션)

int f(int a){Random r=new Random(0x2000A2F47D6Fl);int b=0;for(;a>=0;a--)b=r.nextInt(11)-1;
return b;}

가장 작은 옵션은 아니지만 약간의 재미. X 번 호출 될 때 올바른 값을 생성하는 임의의 시드를 찾았 습니다 (여기서 0> = X <= 9).


영리한. +1
Cyoce를 갖습니다

8

자바 스크립트 (ECMAScript 6) 25

x=>'1060039097'[x]-(x!=6)

자바 스크립트 (ECMAScript 5) 43

function f(x){return'1060039097'[x]-(x!=6)}

업데이트 : edc65는 훨씬 더 나은 기술을 제안했습니다. 칫솔은 훨씬 더 나은 언어를 제안했습니다. 이 시점에서 저의 주요 공헌은 디버깅과 덩어리입니다.


1
ECMAScript 6 (Firefox에서 지원됨)으로 변경하면 간단하게 할 수 x=>[0,-1,5,-1,-1,2,9,-1,8,6][x]있습니다.
칫솔

처음에는 function(x)[0,-1,5,-1,-1,2,9,-1,8,6][x]Firefox 덕분에 거의 게시했습니다 . 어쨌든 이길 수는 없었기 때문에 최고의 호환성을 유지하기로 결정했습니다. 간결하게 언어를 전환하기 시작하면 모든 과제에 대해 내 언어를 정의하기 시작합니다. 어쨌든 ECMAScript 6 버전에 대해 언급하겠습니다. 제안한 이후
Keen

1
같은 개념이지만 더 짧은 (bye bye commas) : x => '106003907'[x]-(x! = 6)
edc65

@ edc65 알다시피, 나는 문자열을 사용하고 싶었고 결과를 숫자로 다시 강요 할 수 있다는 사실에 완전히 비었습니다. 기괴한 경과. 그러나 나는 여전히을 찾지 못했습니다 -(x!=6). 감사합니다.
Keen


6

강타 29

tr 1-9 x5xx29x86|sed s/x/-1/g

예 :

$ echo 0 1 2 3 4 5 6 7 8 9 | tr 1-9 x5xx29x86|sed s/x/-1/g
0 -1 5 -1 -1 2 9 -1 8 6

'sed 표현식 주위 를 생략 할 수 있습니다 . 또한 g스펙은 한 번에 한 자리 만 제공하기 때문에 생략 할 수 있다고 생각합니다.
Digital Trauma

감사. 예를 들어 제출 자체는을 사용하지 않습니다 '. 추천했습니다 g이상 입력!

4

코나 -29

이 함수는 x배열 에서 요소 를 반환합니다0 -1 5...

f:{0 -1 5 -1 -1 2 9 -1 8 6@x}

예 :

> f 2
  5
> f 5
  2
> f 8
  8

벡터 자체가 실제로 허용됩니까?
seequ

@ TheRare : 흠, "알고리즘"이라고 말하지 않기로합니다. 내가 그것을 바꾸고 당신처럼 더 만들 것입니다 ...
Kyle Kanos

더 좋아 보인다, +1.
seequ

4

자바 스크립트 36 37 41

alert('0x'+'65b558f5ec'[prompt()]-6)

ES6 기능으로-27 :

f=v=>'0x'+'65b558f5ec'[v]-6

2
28 :f=v=>~-[1,,6,,,3,10,,9,7][v]
nderscore

@nderscore 당신은 사람들의 코드를 향상시키는 것을 좋아합니다.
seequ

3
@TheRare 나는 가장 짧은 자바 스크립트 코드를 찾으려고 노력하고 있습니다. :) 다른 사람이 이미 좋은 답변을 게시 한 경우 거의 중복 된 새로운 답변을 게시하는 것보다 최적화를 찾는 것이 더 합리적입니다. 저는이 목표를 달성하기 위해 경쟁하기 위해 여기에 있지 않습니다.
nderscore 2016 년

@nderscore 내 생각이 충분히 비슷한 한 같은 사고 방식을 가지고 있습니다. 어쨌든, 좋은 하나.
seequ

@nderscore 당신은 정말 나에게 동기 부여를 주었다. 짧게 만들 수 있는지 확실하지 않지만 시도해 볼 것입니다 :)
core1024

4

클리핑, 11 자

걄럣뉥밈결⓷方分결剩貶

Finally I have found a Windows computer with Visual Studio installed to build its interpreter. And it has defeated my GolfScript code easily.

It reads 18453063256\11\?/11%( in GolfScript.


2
Interesting, but your GolfScript answer still wins. Unless the question states otherwise, length is measured in bytes.
Dennis

@Dennis이 사이트의 3, 4 번째 답변입니다. 몰랐어요 그리고 APL은 예외라고 생각합니다.
jimmy23013

@Dennis 그리고 대부분의 사람들은 Sclipting을 좋아하지 않습니다. :)
jimmy23013

실제로 예외는 아니지만 사람들이 인코딩을 선택하도록합니다. 이 답변의 크기는 UTF-16을 사용하므로 22 바이트입니다. APL은 256 개의 다른 문자 만 사용하며 한 문자가 정확히 1 바이트 인 APL 코드 페이지가 있습니다.
Dennis

@ 데니스 아, 맞아.
jimmy23013

3

J- 28 27 바이트

내가 뭘 좋아하는지 알아? 단순성 (28 바이트) J에서 _1음수 (-1)입니다.

f=:{&0 _1 5 _1 _1 2 9 _1 8 6

약간의 복잡성을 추가하면 27 바이트가 있습니다.

f=:-{&0 2 _3 4 5 3 _3 8 0 3

예:

   f 2
5
   f 6
9
   f 5
2
...

3

CJam-14

입출력 버전 :

"0 5  29 86"q#

스택 버전 (번호가 스택에 있다고 가정) :

[0W5WWY9W8 6]=

http://cjam.aditsu.net/ 에서 시도 하십시오


CJAM에 관한 Wikipedia 기사는 없으며 링크는 빈 피들러로 연결됩니다. 언어 및 확립 된 릴리스에 대한 정보는 어디에서 찾을 수 있습니까?
Panzercrisis 2016 년

이 같은 외모가 있습니다 : sourceforge.net/projects/cjam
Panzercrisis

@Panzercrisis cjam.aditsu.net은 "CJam"는 소스 포지 페이지에 링크 한
aditsu

3

펄, 27 26

카운트는 p깃발을 포함

y/2569/5296/,s/[1347]/-1/

용법:

$ echo 7 | perl -pe y/2569/5296/,s/[1347]/-1/
-1

잠깐, 펄이 방금 J를 이겼나요? :)


+1 I was going to post y+0-9+9a4aa70a13+;$_=9-hex, which is the same length, but your is more original ;)
core1024

1
@core1024 : And it just got shorter ;)
Zaid

It didn't: echo 1 | perl -pe y/2569/5296/,s/[347]/-1/
core1024

@core1024 : I misread the specs, should be fixed now. It's still shorter than the J solution.
Zaid

There really is no concise way to do this in J, as values are strictly typed and numbers can't match strings.
seequ

3

Marbelous 34 bytes

}0
=6=9=2=5=0=8?0
+3-3+3-3....--

It's not the shortest solution, but it's not the longest either.

How it works

}0 spawns a marble representing the first command line input. This marble drops down the next tick, onto the =6 cell. =6 is a comparison cell, it pushes any marble with value 6 down and all others to the right. This line-up of comparison cells pushes marbles right until they equal a desired value. 0 and 8 just fall through and get printed when tehy fall off the bottom of the board, 6 and 2, and 9 and 5 first get 3 added to them, subtracted from them respectively. If a marble doesn't equal any of the desired values, it lands on the ?0 cell, which turn any marble into a 0 marble1. This marble then gets decremented and falls off the board.

1 A ?n marble technically turns any marble into a marble between 0 and n. This has the nice side effect that ?0 turns anything into 0.


2

MATLAB - 35

I would wrap this in a function with n as the only parameter.

f=[0,-1,5,-1,-1,2,9,-1,8,6];
f(n+1)

35 characters.


2

ECMAScript 6, 24

f=x=>~-++'0n5nn29n86'[x]

Using normal JavaScript it would be 33:

alert(~-++'0n5nn29n86'[prompt()])

2

TI-BASIC, 24 22

-1+int(11fPart(11^Ans.0954191904

This encodes the possible outputs in a lookup table stored as a base-11 floating point number; the (N+1)th base-11 digit after the decimal point is extracted from the table to get the value of the inverted digit. In base 11 the number is .106003A097, and the digits of this less one are exactly 0,-1,5,-1,-1,2,9,-1,8,6.

edc65's trick of subtracting one in the case of 6 leads to this 24-byte solution, where ⑩^( is a single one-byte token:

-(Ans≠6)+int(10fPart(.1060039097⑩^(Ans

The string approach is 29 bytes:

-(Ans≠6)+expr(inString("1060039097",Ans+1,1

The array approach (which Ypnpyn also took) is 30 bytes, assuming the number is stored in X:

{1,0,6,0,0,3,10,0,9,7}-1:Ans(X+1

24 -> 22: Removed two extra digits of precision in the magic constant.


This can almost certainly be golfed to 19, and possibly to 18; however, I need to search for the correct numbers.
lirtosiast

2

C - 47 bytes [was 48 Bytes]

f(i){return(int[]){1,0,6,0,0,3,10,0,9,7}[i]-1;}

To add I/O (which other answers didn't always) for 86 bytes:

main(i){i=(int[]){1,0,6,0,0,3,10,0,9,7}[getchar()-48]-1;i<0?puts("-1"):putchar(i+48);}

1
Wow, I had no clue inline array literals like this were a thing. Very nice first answer, and welcome to PPCG! (There is no need to add I/O function submissions are perfectly valid.)
Martin Ender

1

Python - 34

f=lambda n:ord("A@F@@CJ@IG"[n])-65

1
33 f=lambda n:ord(" "[n])-3 working with space codeskulptor.org/#user34_Q7NbNvQy55_0.py
Dylan Madisetti

You might want to explain how and why this works
Riot

Using the ascii table asciitable.com the white spaces chosen are printable in python. it actually looks something like &#002;&#002;&#008;&#002;&#002;&#005;&#012;&#002;&#011;&#009; It's minus 3 for the reason that -1 leaves a null character which is no good, and minus 2 leaves a line feed which is reserved in python
Dylan Madisetti

1

Java, 58 59

int f(int i){int[]a={1,0,6,0,0,3,10,0,9,7};return a[i]-1;}

OR

int f(int i){return new int[]{1,0,6,0,0,3,10,0,9,7}[i]-1;}

You can make your code a bit shorter if you add 1 to each value in array and after [i] substract 1.
barteks2x

@Barteks2x Good point; thanks
Ypnypn

1

JavaScript 42 37

Run it on the console of your browser

alert(~-[1,,6,,,3,10,,9,7][prompt()])

1

C - 117 108 106 77 76 bytes

a[]={1,0,6,0,0,3,10,0,9,7};main(int c,char**b){printf("%d",a[*b[1]-48]-1);}

Not the best language for golfing, but oh well...
Compile with gcc progname.c -o progname. (Ignore the warnings, or add -include stdio.h to the compile command.)

Usage: ./progname <number>

EDIT

As per @bebe's suggestion, here is an example that takes the input from STDIN instead:

C - 68 51 bytes

main(){printf("%d","106003:097"[getchar()-48]-49);}

using d=*b[1]-48 could be a good idea
bebe

@bebe Ah yes, thanks!
BenjiWiebe

1
main(){printf("%d",(int[]){1,0,6,0,0,3,10,0,9,7}[getchar()-48]-1);} sorry for bothering you this much but i find this a bit shorter.
bebe

You can save another character by making the array global so you don't need the cast. a[]={1,0,6,0,0,3,10,0,9,7};main(){printf("%d",a[getchar()-48]-1);}
Allbeert

2
main(){printf("%d","106003:097"[getchar()-48]-49);} 51 bytes
bebe

1

J (24, function)

(the input panel isn't playing nice. Paste the following in a python interpreter and my answer shall be revealed:)

print "f=:{&(_3+3 u:'^C^B^B^E^L^B^K\t')"


1

05AB1E, 13 bytes (non-competing)

0®5®®Y9®8 6¹@

Try it online!

-3 thanks to Emigna.

Explanation:

0®5®®Y9®8 6¹@ Takes an integer from STDIN.
0®5®®Y9®8 6   Push 0, r=-1, 5, r=-1, r=-1, Y=2, 9, r=-1, 8, 6.
           ¹  Push first input item.
            @ Pop and push the 0-indexed stack item at the respective index.

0®5®®Y9®8 6¹@ should work as well.
Emigna

@Emigna I had no idea, thanks!
Erik the Outgolfer

Good thinking with @. Not often you see that used :)
Emigna

@Emigna A byte shorter than )¹è or )sè.
Erik the Outgolfer


1

Jelly, 14 bytes (non-competing)

ị“-5--29-860”V

Try it online!

Explanation:

ị“-5--29-860”V Takes argument as an integer.
 “-5--29-860”  "-5--29-860" (1-indexed string).
ị              Return the xth char of the string above (y) (x=argument).
             V Eval. - is the same as -1.

ịV = žh‡ in 05AB1E
Magic Octopus Urn
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.