정수를 영어 단어로 변환


21

이 코드 골프의 목표는 정수를 영어 단어로 변환하는 것입니다.

프로그램이 입력을 요구합니다. 이 입력이 정수가 아닌 경우 print를 인쇄하십시오 NaN. 정수인 경우 영어 단어로 변환하여이 단어를 인쇄하십시오. 최소 입력 : 0 (영). 최대 입력 : 9000 (만).
따라서 5반환 five(대소 문자는 중요하지 않음) 및 500반환 five hundred또는 five-hundred(대시 중요하지 않음).

다른 규칙들 :

one전에 hundred또는 thousand선택 사양 인 것은 : one hundred정확하지만입니다 hundred(입력이 경우도 100물론).

and예를 들어 단어 one hundred and forty five는 선택 사항입니다.

공백이 중요합니다. 그래서, 대한 500, five-hundred또는 five hundred정확하지만 fivehundred하지 않습니다.

행운을 빕니다!


rgagnon.com/javadetails/java-0426.html 여기에 답이 없습니다 .

SO 의이 답변은 비슷한 일을하지만 코드 골프는 아닙니다.
ST3

답변:


7

펄 281 바이트

print+0eq($_=<>)?Zero:"@{[((@0=($z,One,Two,Three,Four,Five,@2=(Six,Seven),
Eight,Nine,Ten,Eleven,Twelve,map$_.teen,Thir,Four,@1=(Fif,@2,Eigh,Nine)))
[$_/1e3],Thousand)x($_>999),($0[($_%=1e3)/100],Hundred)x($_>99),
($_%=100)>19?((Twen,Thir,For,@1)[$_/10-2].ty,$0[$_%10]):$0[$_]]}"||NaN

수평 위생을 위해 줄 바꿈이 추가되었습니다. 위의 내용은 대화식으로 사용하거나 stdin을 통해 값을 파이프하여 사용할 수 있습니다.

[0, 19999] 범위의 모든 정수 값에 대해 올바르게 작동 하며이 범위 밖의 값은 정의되지 않은 동작을 나타냅니다. 정수가 아닌 값은 0쪽으로 잘 리므로 숫자가 아닌 값만보고 NaN합니다.

샘플 사용법 :

for $n (14, 42, 762, 2000, 6012, 19791, 1e9, foobar, 17.2, -3) {
  print "$n: ", `echo $n | perl spoken-numbers.pl`, $/;
}

샘플 출력 :

14: Fourteen
42: Forty Two
762: Seven Hundred Sixty Two
2000: Two Thousand 
6012: Six Thousand Twelve
19791: Nineteen Thousand Seven Hundred Ninety One
1000000000: Thousand 
foobar: NaN
17.2: Seventeen
-3: Nine Hundred Ninety Seven

"1000000000 : 천"? 그리고 17.2 "NaN"을 인쇄해서는 안됩니까?
DavidC

5
@DavidCarraher "...이 범위를 벗어난 값은 정의되지 않은 동작을 나타냅니다 . 정수가 아닌 값은 0을 향해 잘 리므로 숫자가 아닌 값만보고 NaN됩니다."
primo

저는 Perl 전문가가 아니므로이 질문을합니다 :이 프로그램은 입력을 요구합니까?
ProgramFOX

@ProgramFOX 함수 대신에 stdin에서 값을 읽도록 대화식으로 실행하면 대화 형으로 실행하면 사용자에게 값을 묻는 메시지가 표시됩니다.
primo

13

자바 스크립트 (375)

아마 끔찍한 시도이지만 어쨌든 여기에 간다 ...

alert(function N(s,z){return O="zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),(z?O[s]||O[s-10]||O[s-20]:s<13?N(s,1):s<20?N(s,1)+"teen":s<100?N(a=20+(s/10|0),1)+"ty"+(s%10?" "+N(s%10):""):s<1e3?N(s/100|0)+" hundred"+(s%100?" "+N(s%100):""):s<1e5?N(s/1e3|0)+" thousand"+(s%1e3?" "+N(s%1e3):""):0)||NaN}(prompt()))

예쁘게 인쇄 됨 (함수로) :

function N(s,z) {
  return O = "zero,one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,,for".split(","),
      (z? O[s] || O[s-10] || O[s-20]
       : s < 13?  N(s,1)
       : s < 20?  N(s,1) + "teen"
       : s < 100? N(a=20+(s/10|0),1) + "ty" + (s%10?" "+N(s%10):"")
       : s < 1e3?  N(s/100|0) +  " hundred" + (s%100?" "+N(s%100):"")
       : s < 1e5?  N(s/1e3|0) + " thousand" + (s%1e3?" "+N(s%1e3):"") : 0) || NaN
}

샘플 변환 ( NaN범위를 벗어난 경우, 즉 유효하지 않은 입력 도 출력 됨 ) :

540: five hundred forty
4711: four thousand seven hundred eleven
7382: seven thousand three hundred eighty two
1992: one thousand nine hundred ninety two
hutenosa: NaN
1000000000: NaN
-3: NaN

+1자바 스크립트와 같은 언어에서 더 잘하는 것은 매우 어렵습니다. ( N(s,z) {return1 개의 문자를 저장하기 위해 공간을 제거 할 수 있습니다 )
Math chiller

오, 하하, 그 중 하나를 놓쳤을 것입니다. 나는 또한 O문자열 에서 많은 문자를 놓친 것 같습니다 . 내가 고칠 께 ..
FireFly

11

매스 매 티카 60 57

f = ToString@#~WolframAlpha~{{"NumberName", 1}, "Plaintext"} &

용법:

f[500]

오백

편집하다:

InputString[]~WolframAlpha~{{"NumberName", 1}, "Plaintext"}

3
이것은 실제로 질문에 대답하지 않습니다. 나는 사용자가 숫자를 입력해야한다고 말했고 (예 : 명령 줄 또는 프롬프트 상자 사용) 프로그램이 단어를 명령 줄 또는 메시지 상자에 출력해야한다고 말했습니다. 코드는 단지 그것을 변환하는 함수이며 프로그램은 입력을 요구하지 않습니다.
ProgramFOX

@ProgramFOX는 '사용자가 무언가를 입력했습니다'라고 말합니다. 그것은 '프로그램이 입력을 요구한다'는 의미는 아닙니다.
MrZander

@MrZander : 글쎄, '프로그램은 입력을 요구한다'는 것은 실제로 내가 의미 한 바였습니다. 나는 내 질문을 업데이트하지만, 물론 alephalpha의 답변을지지하지 않으면 불공평 할 것입니다. 그래서 그는 +1을 받았습니다
ProgramFOX

8

리스프, 72 56 자

나는 1) 이것이 오래되었다는 것을 알고 2) 그것이 기능하기 위해 표준 라이브러리에 전적으로 의존한다는 것을 알고 있지만 c-lisp 인쇄 시스템이 이런 종류의 일을 할 수 있다는 사실은 항상 나에게 깊은 인상을주었습니다. 또한 이것은 실제로 사용자로부터 입력을 받아 변환하여 인쇄합니다.

(format t "~:[NaN~;~:*~r~]" (parse-integer (read-line) :junk-allowed t))

총 72 자입니다.

  • :junk-allowed 구문 분석 정수가 오류를 발생시키는 대신 실패시 nil을 리턴합니다.
  • ~:[if-nil~;if-non-nill] nil에 조건부 술어, 필요한 경우 NaN 처리
  • ~:* 입력을 다시 소비하기 위해 인수 해석을 백업합니다.
  • ~r 전체 수정 된 구두점을 제외하고 요청 된대로 숫자를 영어 단어 문자열로 인쇄합니다.

견본:

17823658
seventeen million, eight hundred and twenty-three thousand, six hundred and fifty-eight

192hqfwoelkqhwef9812ho1289hg18hoif3h1o98g3hgq
NaN

Lisp 정보는 주로 Practical Common Lisp에서 제공 합니다.

56 자 이하로 올바르게 골프 편집

(format t "~:[NaN~;~:*~r~]"(ignore-errors(floor(read))))

이 버전은 다소 다르게 작동합니다. 행을 읽고 변환하는 대신 입력을 lisp s- 표현식으로 해석하기 위해 lisp 판독기를 호출하고,이를 숫자로 사용하려고 시도하며, 오류가 발생하면 조건부 문자열을 제공하기 위해 nil을 생성하는 것을 무시합니다. 이것은 정말로 간결한 프로그램을 생산하는 lisp에서 본 첫 번째 사례 일 수 있습니다 ... 재미!

  • (read) lisp 판독기 / 파서를 호출하여 표준 입력에서 하나의 표현식을 읽고 적절한 오브젝트로 변환합니다.
  • (floor) 숫자 형식을 숫자가 아닌 가장 가까운 정수로 변환하려고하면 오류가 발생합니다.
  • (ignore-errors ...) 주석에서 말한 것을 수행하면 동봉 된 표현식의 오류를 포착하고 무시하고 형식 문자열의 NaN 분기를 제공하기 위해 nil을 반환합니다.

질문 old :) 문제는 분명합니다. 헤더에 언어 이름과 문자 수를 포함하도록 답변을 편집했습니다.
ProgramFOX

편집 해 주셔서 감사합니다. 아직 이러한 것들에 대한 Stack * 구문을 얻지 못했습니다. 다시 돌아와서 형식 문자열의 조건부 설명에서 실수를 고쳤습니다.
Tom Scogland

3

PHP, 327 (310) 308 바이트

<?$a=['',one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,0,fif,0,0,eigh];echo($n=$argv[1])>999?$a[$n/1000].' thousand ':'',$n%1000>99?$a[$n/100%10].' hundred ':'',$n?($k=$n%100)<20?($a[$k]?:$a[$k%10]).[teen][$k<13]:[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty '.$a[$k%10]:zero;

숫자를 매개 변수로 사용하고 0 <= n <= 12999에서 작동합니다.

고장

// define names
$a=['',one,two,three,four,five,six,seven,eight,nine,
    ten,eleven,twelve,thir,0,fif,0,0,eigh];
// print ...
echo
    ($n=$argv[1])>999?$a[$n/1000].' thousand ':'',                  // thousands
    $n%1000>99?$a[$n/100%10].' hundred ':'',                        // hundreds
    $n?
        // if remains <20:
        ($k=$n%100)<20?
            ($a[$k]?:$a[$k%10]) // no value at index (0,14,16,17,19)? value from index%10
            .[teen][$k<13]      // append "teen" for $k>12
        // else:
        :[2=>twen,thir,'for',fif,six,seven,eigh,nine][$k/10].'ty '  // tens
        .$a[$k%10]                                                  // ones
    // "zero" for $n==0
    :zero
;

2

SAS, 70 자

data;window w n;display w;if n=. then put 'NaN';else put n words.;run;

windowdisplay문은 SAS 명령 프롬프트를 엽니 다. n라인 1에 입력합니다 . 이것은 SAS 형식 words.을 사용하여 숫자를 단어 또는 일련의 단어로 "and", ""및 "-"와 함께 적절하게 인쇄합니다.


2

PHP

777 자

이것은 끔찍한 시도이지만 허점을 이용했다고 비난 할 수 없으며 운이 좋은 숫자입니다. 팁에 대한 ProgramFOX 덕분입니다.

<?php $i=9212;$b = array('zero','one','two','three','four','five','six','seven','eight','nine');$t='teen';$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t);$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');$e='hundred';$f='thousand';$j=str_split($i);if (strlen($i)===1){$a=$b[$i];}elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}else{$a=$d[$j[0]].' '.$b[$j[1]];}$a = str_replace('zero hundred','',$a);echo $a;function x($j,$k){global $i, $b, $c, $d;if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}else{return $d[$j[$k]].' '.$b[$j[$k+1]];}}

긴 손

<?php
// Input
$i=9212;
// 0-9
$b = array('zero','one','two','three','four','five','six','seven','eight','nine');
// 10-19 (Very tricky)
$t='teen';
$c = array('ten','eleven','tweleve','thir'.$t,$b[4].$t,'fif'.$t,$b[6].$t,$b[7].$t,$b[8].$t,$b[9].$t); 
// Left digit of 20-99
$d = array('','','twenty','thirty','fourty','fifty','sixty','seventy','eighty','ninety');
// Hundreds
$e='hundred';
// Thousands
$f='thousand';
// Split input
$j=str_split($i);
// 1 digit inputs
if (strlen($i)===1){$a=$b[$i];}
// 3 digit input
elseif (strlen($i)===3){$k=1;$a=$b[$j[0]].' '.$e.' '.x($j,$k);}
// 4 digit input
elseif (strlen($i)===4){$k=2;$a=$b[$j[0]].' '.$f.' '.$b[$j[1]].' '.$e.' '.x($j,$k);}
// 10-19
elseif (substr($i, -2, 1)==='1'){$a=$c[$j[1]];}
// 20-99
else{$a=$d[$j[0]].' '.$b[$j[1]];}
// Fix for thousand numbers
$a = str_replace('zero hundred','',$a);
// Result
echo $a;
// Abstracted function last 2 digits for 3 and 4 digit numbers
function x($j,$k){
    global $i, $b, $c, $d;
    // 10-19
    if (substr($i, -2, 1)==='1'){return $c[$j[$k+1]];}
    // 20-99
    else{return $d[$j[$k]].' '.$b[$j[$k+1]];}
}

1
다음과 같은 배열을 작성하여 코드를 줄일 수 있다고 생각합니다 array('zero','one','two').
ProgramFOX

@ProgramFOX 또는 심지어 ['zero','one','two'](php 5.4+). 당신이 괜찮다면 그리고 E_NOTICE, [zero,one,two]물론 작동합니다.
primo

업데이트해야하지만 777은 운이 좋은 숫자입니다.
Goose

노력 +1 코드 골프에서 PHP는 비극적으로 표현됩니다.
primo

1

파이썬 2.x-378

Fireflys의 파생 P은 백만 또는 수조 등을 포함하도록 변경함으로써 어떤 양의 숫자에도 재귀 적으로 사용될 수 있습니다. 또한 최대 999,999 개의 값을 지원합니다

O=",one,two,three,four,five,six,seven,eight,nine,ten,eleven,twelve,thir,,fif,,,eigh,,,,twen,thir,for,fif,,,eigh,".split(",")
P=",thousand".split(',')
def N(s,p=0):
 h,s=divmod(s,1000);x=N(h,p+1)if h>0 else" "
 if s<20:x+=O[s]or O[s-10]+["","teen"][s>12]
 elif s<100:x+=(O[s/10+20]or O[s/10])+"ty"+N(s%10)
 else:x+=N(s/100)+"hundred"+N(s%100)
 return x+" "+P[p]
print N(input())

샘플 테스트 (입력은 <<<, 출력은 >>>) :

<<< 1234
>>> one thousand two hundred thirty four

<<< 999999
>>>  nine hundred ninety nine   thousand nine hundred ninety nine

누군가 내가이 이상한 "버퍼 언더 플로"문제를 설명 할 수 있다면, 그것은 팽창 할 것입니다 ...

<<< -1
>>>  nine hundred ninety nine

<<< -2
>>>  nine hundred ninety eight

print divmod(-2,1000) #-> (-1, 998)
primo

오 당연하지. 나는 절대적인 가치 또는 무언가가 필요할 수도 있다고 생각했습니다. 그러나 -1*1000의 "나머지"가 998있습니다.

1

스마일 베이직, 365 Three Hundred Forty Seven bytes

DIM N$[22]D$="OneTwoThreeFourFiveSixSevenEightNineTenElevenTwelveThirFourFifSixSevenEighNineTwenFor
WHILE LEN(D$)INC I,D$[0]<"_
INC N$[I],SHIFT(D$)WEND
INPUT N
W=N MOD 100C%=N/100MOD 10M%=N/1E3T=W<20X=W/10>>0?(N$[M%]+" Thousand ")*!!M%+(N$[C%]+" Hundred ")*!!C%+(N$[X+10+(X==2)*8+(X==4)*7]+"ty "+N$[N MOD 10])*!T+N$[W*T]+"teen"*(T&&W>12)+"Zero"*!N

마지막 한 자리 또는 두 자리 숫자가 0이면 후행 공백이 있습니다.


0

MOO -55 자

player:tell($string_utils:english_number(read(player)))

또는 "stdout"-42 자로 인쇄 할 필요가없는 경우 : $string_utils:english_number(read(player))

참고 :이 코드는 프롬프트를 표준 출력으로 인쇄 하지 않으며 입력이 숫자가 아닌 경우 zero대신 인쇄 합니다 NaN.

보너스로,이 코드는 moo 언어의 경계 ( 2147483647- -2147483648)를 가진 숫자를 처리 할 수 ​​있습니다 .


0

Wolfram Language 27 40 바이트

기본 기능을 활용, IntegerName,

 Check[Input[]~IntegerName~"Words","NaN"]

위의 내용은 사용자 입력을 요구합니다. 본 구현은 사용자가 정수 이외의 것을 입력하면 "NaN"을 리턴한다.


몇 가지 예 (사전 설정 입력) :

 Check[243~IntegerName~"Words","NaN"]

이백 사십 삼


 Check[1234567890~IntegerName~"Words","NaN"]   

십억, 이백 삼십 사 만, 오백 육십 오만 팔천 구 십팔


 Check["abc"~IntegerName~"Words","NaN"]  

NaN


0

파이썬 2 , 333 바이트

def f(n):S=str.split;D=S('z one two three four five six seven eight nine');K=' fif six seven eigh nine';k=n/1000;n,m=n/100%10,n%100;e,d=m/10,m%10;return' '.join([k and f(k),'thousand']*(k>0)+[D[n],'hundred']*(n>0)+([S('ten eleven twelve thir four'+K)[d]+'teen'*(d>2)]if 9<m<20else[S('twen thir for'+K)[e-2]+'ty']*(e>0)+[D[d]]*(d>0)))

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

1 ~ 999,999 (포함)에 적합합니다.


0

Pyth, 239 242 바이트

L:rjdb6"  +"dAm+cd;"nine"," one two three four five six seven eight""  twen thir for fif six seven eigh"|y_.ey+Wk.e?Y?thZjd,?hZ+@HhZ"ty"""@GeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>H5eZ?hZ+@GhZ" hundred"""c.[03_b]1"thousand"c_jQT3"zero

입력은 [0-999,999] 범위의 정수입니다. 여기에서 온라인으로 사용해보십시오 . 설명이 보류 중입니다.

이전 버전, 매우 유사한 작업이지만 0을 지원하지 않습니다.

L:rjdb6"  +"dJc" one two three four five six seven eight nine"dKc"  twen thir for fif six seven eigh nine"dy_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3

이전 버전에 대한 설명 :

Implicit: Q=eval(input()), d=" "

Step 1: output formatting helper function
L:rjdb6"  +"d   
L               Define a function, y(b):
   jdb          Join b on spaces
  r   6         Strip whitespace from beginning and end
 :              In the above, replace...
       "  +"    ... strings of more than one space...
            d   ... with a single space

Step 2: Define number lookup lists
Jc"..."dKc"..."d   
  "..."            Lookup string
 c     d           Split the above on spaces
J                  Store in J - this is list of unit names
        Kc"..."d   As above, but storing in K - this is list of tens names, without "ty"

Step 3: Bringing it all together
y_.ey+Wk.e?Y?thZjd,?hZ+@KhZ"ty"""@JeZ@+c"ten eleven twelve"d+R"teen"+c"thir four"d>K5eZ?hZ+@JhZ" hundred"""c.[03_b]1"thousand"c_jQT3   
                                                                                                                                jQT    Get digits of Q
                                                                                                                               _       Reverse
                                                                                                                              c    3   Split into groups of 3
  .e                                                                                                                                   Map the above, element as b, index as k, using:
                                                                                                                _b                       Reverse the digits in the group
                                                                                                            .[03                         Pad the above on the left with 0 to length 3
                                                                                                           c      ]1                     Chop at index 1 - [1,2,3] => [[1],[2,3]]
        .e                                                                                                                               Map the above, element as Z, index as Y, using:
          ?Y                                                                                                                               If second element in the group (i.e. tens and units):
            ?thZ                                                                                                                             If (tens - 1) is non-zero (i.e. 0 or >=2):
                   ?hZ                                                                                                                         If tens is non-zero:
                       @KhZ                                                                                                                      Lookup in tens names
                      +    "ty"                                                                                                                  Append "ty"
                                                                                                                                               Else:
                               ""                                                                                                                Empty string
                  ,                                                                                                                            Create two-element list of the above with...
                                 @JeZ                                                                                                          ... lookup units name
                jd                                                                                                                             Join the above on a space - this covers [0-9] and [20-99]
                                                                                                                                             Else:
                                                                     c"thir four"d                                                             ["thir", "four"]
                                                                    +             >K5                                                          Append last 5 element of tens names ("fif" onwards)
                                                            +R"teen"                                                                           Append "teen" to each string in the above
                                      +c"ten eleven twelve"d                                                                                   Prepend ["ten", "eleven", "twelve"]
                                     @                                               eZ                                                        Take string at index of units column - this covers [10-19]
                                                                                                                                           Else: (i.e. hundreds column)
                                                                                       ?hZ                                                   If hundreds column is non-zero:
                                                                                           @JhZ                                                Lookup units name
                                                                                          +    " hundred"                                      Append " hundred"
                                                                                                         ""                                  Else: empty string
                                                                                                                                         Result of map is two element list of [hundreds name, tens and units name]
      Wk                                                                                                                                 If k is nonzero (i.e. dealing with thousands group)...
     +                                                                                                              "thousand"           ... Append "thousand"
    y                                                                                                                                    Apply output formatting (join on spaces, strip, deduplicate spaces)
                                                                                                                                       Result of map is [units group string, thousands group string]
 _                                                                                                                                     Reverse group ordering to put thousands back in front
y                                                                                                                                      Apply output formatting again, implicit print
당사 사이트를 사용함과 동시에 당사의 쿠키 정책개인정보 보호정책을 읽고 이해하였음을 인정하는 것으로 간주합니다.
Licensed under cc by-sa 3.0 with attribution required.