| Bytes | Lang | Time | Link |
|---|---|---|---|
| 062 | Raku Perl 6 rakudo | 250415T202049Z | xrs |
| 065 | AWK | 250411T154058Z | xrs |
| 054 | APL | 220720T130713Z | Vadim Tu |
| 002 | Vyxal | 220720T202251Z | naffetS |
| 079 | Lexurgy | 220720T161817Z | bigyihsu |
| 035 | Jelly | 161217T112556Z | Erik the |
| 068 | PHP | 140621T083024Z | Mr. Alie |
| 159 | Racket | 161217T130751Z | rnso |
| 011 | Factor | 161218T025701Z | cat |
| 011 | Wolfram | 161217T143536Z | swish |
| 089 | C | 160720T181759Z | user5634 |
| 079 | /// | 160721T083626Z | Erik the |
| 061 | Sprects | 160721T084003Z | Erik the |
| 101 | F# | 140621T152226Z | Jwosty |
| 088 | C | 140623T200833Z | aragaer |
| 103 | Befunge 98 | 140621T053324Z | Justin |
| 075 | Haskell | 140630T181528Z | DrJPeppe |
| 008 | bash say OS X | 140623T111236Z | CousinCo |
| 104 | swipl | 140623T105003Z | rpax |
| 053 | In AppleScript 53 chars. | 140626T202543Z | TheMaske |
| 7116 | In Java 7 and newer 116 chars | 140626T191311Z | TheMaske |
| 028 | Python 34 / | 140625T042037Z | Register |
| nan | 140623T031402Z | MB6 | |
| 143 | Apple Swift | 140623T091251Z | Losiowat |
| nan | 140621T115746Z | rene | |
| 050 | GolfScript | 140625T100815Z | Ilmari K |
| 009 | BASH | 140625T043758Z | Register |
| 064 | Bash | 140625T010540Z | John B |
| 064 | Ruby | 140621T083839Z | Mohammad |
| 034 | Sclipting | 140624T173531Z | Timwi |
| 052 | Python 3 + Japanese 34 characters | 140624T173507Z | hdante |
| 111 | C | 140624T140558Z | Jerry Co |
| 063 | Powershell | 140624T134000Z | DarkAjax |
| 185 | Java 7 | 140624T060453Z | Baby |
| 090 | sed | 140624T040647Z | Kevin |
| 055 | Perl | 140621T070919Z | Heiko Ob |
| 062 | PHP 5.5 | 140623T193431Z | mcrumley |
| 022 | Common Lisp | 140621T223154Z | filcab |
| 084 | Javascript | 140623T181135Z | Cilan |
| 064 | Python 2.x 65 | 140621T061637Z | Willem |
| 071 | PowerShell | 140623T170416Z | microbia |
| 073 | Javascript | 140621T050215Z | nderscor |
| 067 | R | 140623T143511Z | plannapu |
| 086 | Batch | 140623T112751Z | Οurous |
| 089 | Haskell | 140623T110108Z | rpax |
| 050 | CJam | 140622T123915Z | aditsu q |
| nan | 140623T100808Z | 18446744 | |
| 130 | Extended BrainFuck | 140623T082654Z | Sylweste |
| 078 | Zozotez Lisp | 140623T082520Z | Sylweste |
| 068 | Racket / R5RS Scheme | 140621T171423Z | Sylweste |
| 074 | Powershell | 140621T151756Z | rene |
| 066 | Ruby | 140623T053402Z | Siva |
| 051 | BASH | 140621T063650Z | Eric Lag |
| 042 | Shell | 140622T182345Z | Digital |
| 123 | In AppleScript 123 chars. | 140622T111020Z | TheMaske |
| 009 | Bash with bsdgames | 140622T162910Z | user1640 |
| 068 | Ruby | 140622T160430Z | Colt |
| 058 | Rebol | 140622T153828Z | draegtun |
| nan | 140622T153237Z | el.pesca | |
| 154 | ObjectiveC | 140622T065244Z | Milo |
| 064 | pure Bash | 140621T200431Z | user1640 |
| 064 | Bash + coreutils | 140622T031006Z | Digital |
| 068 | POSIX SHELL | 140621T230002Z | technosa |
| nan | 140621T194905Z | Jack | |
| 133 | C++11 | 140621T205620Z | Anti |
| 043 | CJam | 140621T050154Z | Dennis |
| 162 | DOS Batch 162 Chars incl' line breaks | 140621T194936Z | Ruslan |
| 053 | J 57 or | 140621T091601Z | seequ |
| 068 | Javascript | 140621T082623Z | edc65 |
| 060 | Perl | 140621T154505Z | Dennis |
| 046 | Oracle SQL | 140621T134055Z | Ben |
| 064 | Python 2 | 140621T051622Z | grc |
| 061 | Tcl | 140621T115759Z | slebetma |
| 075 | VBScript | 140621T054618Z | comforta |
| 051 | GolfScript | 140621T050213Z | Justin |
Raku (Perl 6) (rakudo), 62 bytes
{"one two threefour five six seveneightnine".comb(5)[$_-1]}
AWK, 65 bytes
{split("one two three four five six seven eight nine",x)}$0=x[$1]
APL, 54 bytes
⎕⊃↓9 5⍴'ONE TWO THREEFOUR FIVE SIX SEVENEIGHTNINE '
Lexurgy, 79 bytes
a:
{\1,\2,\3,\4,\5,\6,\7,\8,\9}=>{one,two,three,four,five,six,seven,eight,nine}
Simple substitution.
Jelly, 35 bytes
ị“¡5ç“¡Ḃḥ“¡Ị¿“Ɱ9“ƁẆ“¡⁹)“¡°Ṗ“z⁷“¡'Ṡ»
Explanation:
“¡5ç“¡Ḃḥ“¡Ị¿“Ɱ9“ƁẆ“¡⁹)“¡°Ṗ“z⁷“¡'Ṡ» List of numbers 1-9 as words.
ị xth element of y.
PHP, 93 73 68 bytes
<?=explode(' ','one two three four five six seven eight nine')[1-1];
Racket 159 bytes
(string-join(map(λ(x)(list-ref(list"zero""one""two""three""four""five""six""seven""eight""nine")(string->number(string x))))(string->list(number->string n))))
Ungolfed:
(define(f n)
(string-join
(map (λ (x)
(list-ref [list "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"]
(string->number(string x))))
(string->list (number->string n)))))
Testing:
(f 10357)
Output:
"one zero three five seven"
17 bytes can be saved if number is sent enclosed in double quotes:
(define(f n)
(string-join
(map (λ (x)
(list-ref [list "zero" "one" "two" "three" "four" "five" "six" "seven" "eight" "nine"]
(string->number(string x))))
(string->list n))))
(f "10357")
"one zero three five seven"
Factor, 11 bytes
a builtin: number>text.
Wolfram, 11
There is a function for that of course: IntegerName
C, 92 89 bytes Japanese(Hiragana , Katakana)
Hiragana (ひらがな)
h(n){char*h="いちに さんし ご ろくななはちきゅ";printf("%.6s%s",h+--n*6,n^9?"":"う");}
Katakana (カタカナ)
k(n){char*k="イチニ サンシ ゴ ロクシチハチキュ";printf("%.6s%s",k+--n*6,n^9?"":"ウ");}
///, 80 79 bytes
/_/\/\///0/zero_1/one_2/two_3/three_4/four_5/five_6/six_7/seven_8/eight_9/nine/
Append the number at the end of the code (this is ///'s input).
Sprects, 61 bytes
#<INPUT>#9nine#8eight#7seven#6six#5five#4four#3three#2two#1one#0zero
Replace <INPUT> with the number, because Sprects does not have any other form of input (bytecount is without the "input".)
F# - 101
printf"%s"["one";"two";"three";"four";"five";"six";"seven";"eight";"nine"].[System.Console.Read()-49]
For a newline but 108 bytes, change printf to printfn.
It's a naïve solution that just fetches the given index of that hardcoded list. I would have loved to use base64 encoding and/or a regex to split a string into an array (so the elements would be separated with instead of ";"), but both of those would just make the solution longer, due to namespaces. Why can't they just be in System like everything else? :'(
C - 93 91 89 88 bytes (thanks Cool Guy)
main(x){scanf("%d",&x);write(1,5*--x+"one two threefour five six seveneightnine",5);}
Old version with arguments instead of scanf:
main(int c,char**a){write(1,"one two threefour five six seveneightnine"+*a[1]*5-245,5);}
Cryptic version (code-trolling?):
This one is somewhat longer but at least no space is wasted on spaces (only tabs and newlines ... and one space in function header).
main(int c,char**a){
*a="039018342675onetwosixfourfivenineseveneightthree";
c=*(*a+*a[1]-46)-39;
write(1,c/3*(c-9)-*(*a+c/3-3)+60+*a,c/3);
}
Magic sequence 018342675 can be calculated as x+=6*!(x%3)-1;x%=9; but in the end I decided to use strings for everything.
Yet another version (different arrangement of numbers, easier to calculate position):
main(int c,char**a){
*a="038146257onefourseventwofiveeightsixninethree";
c=*(*a+*a[1]-49)-45;
write(1,*a+c*4+!(c%3)-4,3+c%3);
}
Befunge 98, 116 105 103 bytes
&1- v
vvvvvvvvvj<
"""""""""
etnxereoe
nheivuewn
igvsiorto
nie"ffh""
"es ""t
"" "
>>>>>>>>>4k,@
Befunge was not made for this...
Explanation:
&1- ;Grab the input number (`n`) and subtract 1 from it
&1- v ;Start moving downwards
< ;Start moving leftwards
j ;Jump `n - 1` characters to the left.
vvvvvvvvvj ;Redirect each of the possible locations to jump to, sending the IP down.
" ;If `n` was 1, push `o, n, e` onto the stack (`o` is at the bottom)
e
n
o
"
" ;If `n` was 2, push `t, w, o` onto the stack
o
w
t
"
*
*
*
" ;If `n` was 9, push `n, i, n, e` onto the stack
e
n
i
n
"
>>>>>>>>> ;Collect all the different possible positions the IP could be in, and send it right
>>>>>>>>>4k, ;Print the top 5 chars. If there are less than 5, the rest are null characters. This is allowed
@ ;End of program
Haskell 75
I know I'm a little late to the party, but thought I might as well:
fmap(words"_ One Two Three Four Five Six Seven Eight Nine"!!)readLn>>=print
bash say (OS X): 3 8
"Your goal is to convert a whole number between 1-9 into the word it represents"
Last time I checked, spoken words are words as well. Previous attempt (accepts no input)
say 4
Edit, must be able to read input:
say|read
Type any number and the word comes out. I know the end date is due, but in my opinion I should have won the contest.
Example audio file: four.aiff
swipl: 104 bytes
get_char(C),number_codes(X,[C]),nth0(X,[o,one,two,three,four,five,six,seven,eight,nine,ten],Y),write(Y).
Brainfuck: 672 bytes
+>,-------------------------------------------------[-[-[-[-[-[-[-[[-]+
[------->++<]>.-----.+++++.---------.[-]<[-]>[-]]<[[-]--[----->+<]>-.++
++.--.+.++++++++++++.[-]<[-]>[-]][-]<[-]>[-]]<[[-]+[--------->++<]>+.++
++[->+++<]>.[--->+<]>-.+[->+++<]>.+++++++++.[-]<[-]>[-]][-]<[-]>[-]]<[[
-]+[--------->++<]>+.----------.-[--->+<]>.[-]<[-]>[-]][-]<[-]>[-]]<[[-
]--[----->+<]>.+++.[->++++++<]>.+[->+++<]>.[-]<[-]>[-]][-]<[-]>[-]]<[[-
]--[----->+<]>.+++++++++.++++++.---.[-]<[-]>[-]][-]<[-]>[-]]<[[-]------
--[-->+++<]>.------------.++++++++++.-------------..[-]<[-]>[-]][-]<[-]
>[-]]<[[-]--------[-->+++<]>.+++.--------.[-]<[-]>[-]][-]<[-]>[-]]<[[-]
+[------->++<]>+.-.---------.[-]]
In AppleScript ; 53 chars.
say(display dialog""default answer"")'s text returned
Here is a nicer version :
set n to text returned of (display dialog "?" default answer "")
say n
This script takes the input in a dialog. Then it tells the output to the user. The user does not even have to read ! This solution works even for people who are unable to read.
In Java (7 and newer) ; 116 chars
public class A{public static void main(String[] a){System.out.print(Character.getName(48+Integer.parseInt(a[0])));}}
This program takes the input number as command-line argument, and outputs the letters in the console.
Example :
- Input :
4 - Output :
DIGIT FOUR
Python 34 / 28
For this code to work, you have to install num2words module. Also thanks to @undergroundmonorail for his suggestion.
import num2words
num2words(input())
If input() is not necessary , and user is allowed to enter number directly into code, then
import num2words
num2words(3)
will also work.
Python
here is a simple answer. In python, if you have a key-val mapping pair, you use a dict. this program waits for an input, (0-9) and converts it
n={
1:'one',2:'two',3:'three',4:'four',5:'five',6:'six',7:'seven',8:'eight',9:'nine',0:'zero'}
print n.get(int(raw_input()))
Apple Swift : 143
Not a winner, but my first Code-Golf, so hello everyone!
for i in 1..C_ARGC{print(["zero","one","two","three","four","five","six","seven","eight","nine"][String.fromCString(C_ARGV[Int(i)]).toInt()!])}
What I like about this is that the lookup table is defined in place in print so I could shave a few chars by removing the variable definition for it.
Accepts any number of input arguments, provided that they are separeted with spaces.
C# - 127 ( 86 / 46)
If you only take the executable part...
Console.Write(((HourOfDay)Console.Read()-48));
and if HourOfDay would have been part of the the System namespace you would need 46 chars. Unfortunately it sits in System.DirectoryServices.ActiveDirectory which makes it 86...the other noise spoils it.
This is compileable and runnable from the commandline (127 chars):
using System;class P{static void Main(){Console.Write((System.DirectoryServices.ActiveDirectory.HourOfDay)Console.Read()-48);}}
if saved to a file called cg2.cs
csc cg2.cs /r:System.DirectoryServices.dll && cg2
How does this work?
HourOfDay is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the name of the value. You can cast an int to an enum. Console.Read() reads a character from the input stream represented as an integer. typing '1' gives 49, substract 48 to get 1, cast/box to HourOfDay to return 'One'.
GolfScript, 50 bytes
I wanted to see if I could beat Quincunx's 51-byte self-contained GolfScript solution. Turns out that, with enough tricks, yes, I can — by one byte.
Since one of the tricks I'm using is the use of bytes outside the printable ASCII range, the resulting program is cannot be directly pasted here. Instead, I'm providing a hex dump of it; users on Unixish systems can use xxd -r to reconstruct the actual 50-byte GolfScript program from the hex dump:
0000000: 7e6e 270b 97eb 442f e166 9894 9f00 c63c ~n'...D/.f.....<
0000010: 8128 73a3 9b55 5065 a9fb f06a 2727 ff16 .(s..UPe...j''..
0000020: 277b 6261 7365 7d2f 2b6e 2f3d 7b39 392b '{base}/+n/={99+
0000030: 7d25 }%
The basic trick used to generate this program is simple: I compress the long string literal that makes up most of Quincunx's code by subtracting 99 (the ASCII code of the letter c) from the character values, interpreting the resulting values as a number in base 22 (enough to encode the letters up to x) and then re-encode the resulting number in base 255 to produce the unprintable byte string that makes up most of the first half of my program. The rest of the program then reverses this process, decoding the string back into something printable.
(Since the lowest letter actually present in the number names is e, I could've shortened the byte string further by subtracting 101 from the ASCII codes and using base 20. However, subtracting 101 would've mapped the letter o to a newline, which I'm using as the number delimiter because it's conveniently available as the built-in constant n in GolfScript. Working around that would cost me more than the one byte that using a lower base would save. Using the offset 99 leaves the newline corresponding to the letter m, which is conveniently absent from the number names.)
Here's a de-golfed version of the program:
~ # eval the input, turning it into a number
n # push a newline onto the stack; we'll need it later
# this is the byte string encoding the number names:
"\x0B\x97\xEBD/\xE1f\x98\x94\x9F\x00\xC6<\x81(s\xA3\x9BUPe\xA9\xFB\xF0j"
# convert the encoded string from base 255 to base 22
# (and, incidentally, from a string to an array):
"\xFF\x16" {base}/
+ # prepend the newline pushed earlier to the array, re-stringifying it
n/ # split the resulting string at newlines
= # pick the substring corresponding to the input number
{99+}% # add 99 to the character values in the chosen substring
Bash, 64
d=(z one two three four five six seven eight nine)
echo ${d[$1]}
Takes the first argument as a number and uses it as an array index to print the corresponding word.
Ruby 64
p %w?one two three four five six seven eight nine?[$*[0].to_i-1]
Sclipting (34)
껆뭮뉒롴덶묬덆둲뉖넬뉦뭵댢롦늗뉥껇꽩뎂롳뉗뉥닢롥늖덨덂롮늖멥壹坼⓶掘
This is very straight-forward. Remember the user input is first on the stack.
껆뭮뉒롴덶묬덆둲뉖넬뉦뭵댢롦늗뉥껇꽩뎂롳뉗뉥닢롥늖덨덂롮늖멥
- Push the string
",one,two,three,four,five,six,seven,eight,nine"
壹
- Retrieve the first character from that string (but leave the string on the stack)
坼
- Regular expression string-split. Result:
["", "one", "two", "three", "four", "five", "six", "seven", "eight", "nine"]
⓶
- Swap the top two elements (so the input is now on top)
掘
- Get nth element from the list, leaving only the result on the stack.
Python 3 + Japanese - 34 characters (52 bytes)
Not sure if this counts:
print('九八七六五四三二一'[-int(input())])
Numbers were taken from:
C 111
#include <stdio.h>
int main(){printf("%.5s","one two threefour five six seveneightnine"+5*(getchar()-'1'));}
The length here is carefully engineered so I can interpret it as binary and convert that to decimal. At only 7 characters, I'm confident I have a winner!
Powershell 63
(-split"X one two three four five six seven eight nine")[$args]
(The default delimiter in Powershell is whitespace)
Java 7 - 185
class Num{
public static void main(String[] args) {
System.out.print("ONE,TWO,THREE,FOUR,FIVE,SIX,SEVEN,EIGHT,NINE".split(",")[(new java.util.Scanner(System.in)).nextInt()-1]);
}}
sed 90
It's really a trivial program (the brute force method); I wouldn't have bothered, except that it beats a surprising number of answers here.
s/9/nine/
s/8/eight/
s/7/seven/
s/6/six/
s/5/five/
s/4/four/
s/3/three/
s/2/two/
s/1/one/
Perl, 55
$_=(nine,eight,seven,six,five,four,three,two,one)[-$_]
It is run with option -p (+1 byte), e.g.:
perl -pe '$_=(nine,eight,seven,six,five,four,three,two,one)[-$_]'
Input is expected in STDIN and output is written to STDOUT.
The code just generates an array and selects the right element. Option -p takes care of reading the input line into $_ and prints the result in $_.
Variations:
With trailing new line (+3):
$_=(nine,eight,seven,six,five,four,three,two,one)[-$_].$/or (same byte count):
s/./(nine,eight,seven,six,five,four,three,two,one)[-$&]/e
Update:
Using bare words instead of
qw[...](thanks Zaid).Negative index saves a byte (thanks aragaer).
PHP 5.5 (62)
<?=[0,one,two,three,four,five,six,seven,eight,nine][$argv[1]];
If you read from standard input it goes up to 66 characters.
<?=[0,one,two,three,four,five,six,seven,eight,nine][fgetc(STDIN)];
Common Lisp - 22 bytes
Here's a general one (not just for one-ten):
(format nil"~R"(read))
Oh, you want ordinals (first, second, ... three-hundredth...)? Ok!
(format nil"~:R"(read))
Javascript, 94 92 84 bytes
alert(['one','two','three','four','five','six', 'seven','eight','nine'][prompt()-1])
Python 2.x - 65 64
Not as good as @grc 's answer, but certainly more legible :-)
'one two three four five six seven eight nine'.split()[input()-1]
One less char, thanks to @flornquake
'nine eight seven six five four three two one'.split()[-input()]
PowerShell (71)
PS > "one,two,three,four,five,six,seven,eight,nine".split(",")[$(read-host)]
Works for valid inputs.
Javascript 73
alert('0one0two0three0four0five0six0seven0eight0nine'.split(0)[prompt()])
69
alert(btoa("ôéÞõ5õ1ëxO_¢êý|Þöȱõ'xß^hSôا{Ý").split(9)[prompt()])
R, 67 characters
scan(t='one two three four five six seven eight nine',w='')[scan()]
First part creates a vector containing the names, second part subset it according to user input (indices are 1-based in R).
Batch - 86
Far shorter than the other batch answer, and actually surprisingly competitive.
for /f "tokens=%1" %%1 in ("one two three four five six seven eight nine") do echo>%%1
Used as filename.bat number, and the output is in the form of a file with the name of the correct number.
Haskell : 89
do x<-readLn;print$[[],"one","two","three","four","five","six","seven","eight","nine"]!!x
CJam - 50
This is a plain ASCII solution that uses HTTP requests (this is allowed in the question):
"aj21.com/"r+g
On the server there are 9 plain-text files named 1, 2, ..., 9, each containing the corresponding word.
Total size: 14 + 3 ("one") + 3 ("two") + 5 + 4 + 4 + 3 + 5 + 5 + 4 = 50.
It can be golfed more by using a shorter domain.
The online interpreter doesn't support HTTP requests, so the program needs to be run using the java interpreter.
Forth (gforth)
36 base ! nine eight seven six five four three two one 0
Usage:
1 pick . ONE ok
2 pick . TWO ok
3 pick . THREE ok
4 pick . FOUR ok
5 pick . FIVE ok
6 pick . SIX ok
7 pick . SEVEN ok
8 pick . EIGHT ok
9 pick . NINE ok
where ok is printed by the interpreter.
In fact, I do not know how to count characters in this. One might even say that this is not a program.
Extended BrainFuck: 130
{z(-))}{b&z)<(-}+>,49-(-(-(-(-(-(-(-((-)<-|<nine<&z<(-|<eight<&b
|<seven<&b|<six<&b|<five<&z)<(-|<four<&b|<three<&b|<two<&b|<one<&z
EBF is a superset of BrainFuck but it has not it's own runtime. It compiles to pure BrainFuck.
Zozotez Lisp: 122 78
((\(1 2 3 4 5 6 7 8 9)(p(e(r))))'one'two'three'four'five'six'seven'eight'nine)
Zozotez is a LISP-1 interpreter written in Extended BrainFuck. It's only data types are symbols and cons and supports first class functions and macros
Racket / R5RS Scheme: 71 68
(vector-ref'#(z one two three four five six seven eight nine)(read))
It runs in the REPL of R6RS and R7RS with base library loaded too.
Powershell - 91 74
[Enum]::ToObject([System.DirectoryServices.ActiveDirectory.HourOfDay],[Console]::Read()-48)
Found out how to cast to remove the Enum and ToObject call:
[System.DirectoryServices.ActiveDirectory.HourOfDay]([Console]::Read()-48)
How does this work?
HourOfDay is an enum type so we can use names instead of magic constants. Enum types have a ToString() implementation that gives you the name of the constant value. You can cast an int to an enum. Console.Read() reads a character from the input stream represented as an integer. typing '1' gives 49, substract 48 to get 1, cast to HourOfDay to return 'One'.
Because powershell does a ToString on all objects being written to the output stream and doesn't need the fluff to turn this into an executable this all that is needed besides powershell...
Ruby - 66
$><<%w[a one two three four five six seven eight nine][gets.to_i]
BASH 51
So I made another one using my second idea plus some help from others:
set one two three four five six seven eight nine
$X
Where 'X' is the number you want.
BASH 48 (67)
67 with \n line breaks
I'm not sure if this totally counts, because it's reading from a file, but:
sed -n Xp a
Where "X" is the input and where a is a file with:
one
two
three
four
five
six
seven
eight
nine
The file is 36 chars, and the bash command is 13.
How it works:
Each line in the file is numbered, starting with 1. So 'one' is on the 1st line, 'two' on the 2nd. The command,
sed -n 'Xp' asays, "Please print what's listed on line 'X' of file 'a'"sedis a Unix stream editor.-nmeans be silent, or only essentially ignore everything else.Xpmeans print what's on line 'X'.
Shell, 42 bytes
cat $1
This relies on files in the current directory, one for each digit. The lengths of the files are included in the score:
ubuntu@ubuntu:~/n$ ls -l
total 40
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:39 1
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:40 2
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:40 3
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:40 4
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:41 5
-rw-rw-r-- 1 ubuntu ubuntu 3 Jun 22 11:41 6
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:41 7
-rw-rw-r-- 1 ubuntu ubuntu 5 Jun 22 11:41 8
-rw-rw-r-- 1 ubuntu ubuntu 4 Jun 22 11:41 9
-rwxrwxr-x 1 ubuntu ubuntu 6 Jun 22 11:42 n.sh
ubuntu@ubuntu:~/n$
Example Output:
$ ./n.sh 4
four$
$ ./n.sh 7
seven$
$
In AppleScript ; 123 chars.
{"one","two","three","four","five","six","seven","eight","nine"}'s item((display dialog""default answer"")'s text returned)
This script takes the input in a dialog. Then it gives the output in AppleScript’s result.
Example :
- Input :
6 - Output :
"six"
Here is a nicer version :
set l to {"one","two","three","four","five","six","seven","eight","nine"}
set n to text returned of (display dialog "?" default answer "")
display dialog (l's item n) buttons ("OK") default button 1
This version displays the output in a nice dialog.
Example :
- Input :
9 - Output :
nine
[ Answer edited ; slightly improved the dialog for the input ; still 124 chars. Answer edited again ; now 1 char less ! ]
Bash (with bsdgames), 9
number -l
Reads from standard input.
I don't know why there's a utility for this, but whatever.
Ruby 68
v=%w(one two three four five six seven eight nine);p v[gets.to_i-1]
Would love tips on how to get it down further!
Rebol - 58
pick[one two three four five six seven eight nine]do input
Example from Rebol console:
>> pick[one two three four five six seven eight nine]do input
9
== nine
Perl 36 (58 standalone)
use Number::Spell;say spell_number<>
Or, without additional modules:
say qw(one two three four five six seven eight nine)[<>-1]
Objective-C - 154 bytes
This one is kind of cheating a little bit because Objective-C has a built in class just for this but I don't see anything in the rules that says I can't do that so here it is!
int i;
scanf("%d",&i);
NSNumberFormatter *f=[[NSNumberFormatter alloc] init];
[f setNumberStyle:5];
NSString *s=[f stringFromNumber:@(i)];
NSLog(@"%@",s);
(pure) Bash, 64
Takes input as its first argument, assuming valid input.
v=(o one two three four five six seven eight nine)
echo ${v[$1]}
Creates an array v, then accesses the element specified on the input. Since arrays are zero-indexed, I had to add a 0th element as a placeholder. Alternatively (thnx @DennisWilliamson for pointing this out):
v=(one two three four five six seven eight nine)
echo ${v[$1-1]}
Bash + coreutils, 64
Non-competitive compression concept
xxd -p<<<TàPnàõ:àsÀ~®@ãCN|tr 0-9a-d \\ng-inor-x|sed -n $1p
Some of the exotic characters here may not render well, so this script may be reconstructed from its base64 representation:
base64 -d <<< eHhkIC1wPDw8VOCLUIJu4PWWDzrgc8B+rkDjEoBDTnx0ciAwLTlhLWQgXFxuZy1pbm9yLXh8c2VkIC1uICQxcA==
Example output
$ ./n.sh 1
one
$ ./n.sh 9
nine
$
Explanation
It occurred to me that the string one two three four five six seven eight nine contains only the letters efghinorstuvwx and a space separator - 15 character values in total. Thus each character can potentially be represented in 4 bits, or 2 characters per 1 byte. We can use the hex representation of a byte as an easy way to split each byte into two hex digits. We can then transform the hex digits back to the letters we require using tr or similar. As luck would have it, rstuvwx are consecutive, so may be expressed as r-x to tr. The encoding is arranged such that e and f are left as-is, and that the words are line-break separated, so we can use sed to ouptut just the line we need.
This decoding process ends up using a fair amount of extra space, so makes this answer non-competitive as a shell-script-style answer, but may be a useful concept in other languages.
POSIX SHELL: 68
Similar to Eric's Bash, without the bashisms (using set to mimick an array using $@) and eval to handle indirection (in bash this could just be echo ${!A} without the eval)
A=$1
set one two three four five six seven eight nine
eval echo \$$A
I know I'm not going to win but I just want to participe...
C++11 172
#include <iostream>
int main(){ auto a = { "one", "two", "three", "four", "five", "six", "seven", "eight", "nine" };printf("%s", *(a.begin() + getchar() - '0' - 1));}
Javascript - 79 - 69 68: (run on dev console)
["one", "two", "three", "four","five","six","seven","eight","nine"][prompt()-1]
"one,two,three,four,five,six,seven,eight,nine".split(',')[prompt()-1]
",one,two,three,four,five,six,seven,eight,nine".split(',')[prompt()]
C++11 - 133
My answer in C++:
#include<iostream>
main(){char*n[]={"one","two","three","four","five","six","seven","eight","nine"};std::cout<<n[std::cin.get()-'1'];}
The total amount of bytes is 133.
CJam, 45 43 bytes
"^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256bKb'ef+'j/li=
The above uses ^ and M- notation, since some characters are unprintable.
At the cost of 9 more bytes, unprintable characters can be avoided:
" one two three four five six seven eight nine"S/li=
How it works
" Convert the string into an integer by considering it a base-256 number. ";
"^AM-^L8M-xM-^L^US^_M-^WrM-rM- 1M-s^CHM-|M-X^HE,M-qM-^EM-q4"256b
" Convert the integer from above into an array by considering it a base-20 number. ";
Kb
" Add the ASCII character code of “e” to all elements of that array. This casts to char. ";
'ef+
" So far, we've pushed the string “jonejtwojthreejfourjfivejsixjsevenjeightjnine”. ";
" Split the the above string where the character “j” occurs. ";
'j/
" Read an integer from STDIN and push the corresponding substring. ";
li=
Example
$ base64 -d > convert.cjam <<< IgGMOPiMFVMfl3LyoDHzA0j82AhFLPGF8TQiMjU2YktiJ2VmKydqL2xpPQ==
$ wc -c convert.cjam
43 convert.cjam
LANG=en_US cjam convert.cjam <<< 5
five
DOS Batch - 162 Chars (incl' line breaks)
This answer was inspired by @grc's Python answer, although I did have something similar in mind.
@setlocal enabledelayedexpansion
@set s="ottffssennwhoiieiieoruvxvgn ere ehe e nt
@set /a c=%1
@set z=!s:~%c%,1!
@if _%z%==_ exit /b
@echo %z%
@%0 %c%+9
Usage:
[Filename] [number]
For example, if the code is in a file called speak.bat, and you want to see the number "five", you would run it as:
speak 5
Also, the output is top-to-bottom, not left-to-right! So instead of
five
you will see
f
i
v
e
J - 68 or 60 57 or 53 bytes
Interactive version (stdin):
>one`two`three`four`five`six`seven`eight`nine{~<:".1!:1]1
Function version:
f=:one`two`three`four`five`six`seven`eight`nine>@{~<:
Explanation:
f=:one`two`three`four`five`six`seven`eight`nine>@{~<:
<: Decrease by one
{~ Get the correct string
>@ Unbox
".(1!:1)1 reads a string and converts it to integer
Javascript 68
Atob / btoa can be a poor's man compressing tool
(but if you want to try this in console, you cannot copy from the formatted text you see at once. Go to 'edit' and copy from the source panel)
Markdown editor does not like some of the characters in this answer: some characters get lost at saving. Still, I think it's an editor problem, not mine. The lost characters are perfectly valid 8 bit unicode chars.
(Or else I'm wrong, if this issue was already debated in meta, let me know)
Here is the version with offending characters escaped, each sequence \xNN should count 1
alert(btoa("×C§{Dð£Dáç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[prompt()])
Simple Test
In firefox console:
[0,1,2,3,4,5,6,7,8,9]
.map(x=>x +',' btoa("×C§{Dð£Dáç´\x16\x8b«ÐX¯{D¢ÇD\x9e½éô\x12(!·Cb\x9dí").split(0)[x])
Perl, 60 bytes
$_=(ZOneTwoThreeFourFiveSixSevenEightNine=~/.[a-z]*/g)[$_]
Requires the -p switch (two bytes).
Example
$ perl -p convert.pl <<< 5
Five
How it works
-preads from STDIN and saves the result in$_.=~/.[a-z]*/gsplits the preceding bareword into substrings of one (uppercase) letter followed by any number of lowercase letters.(…)collects the substrings into an array.[$_]retrieves the substring corresponding to the user input.$_=…saves the result in$_.-pprints the value of$_.
Oracle SQL - 46
select to_char(to_date(&1,'j'),'jsp')from dual
This does include a standard loophole, I admit, but the SQL is shorter than Golfscript; I couldn't resist!
It works by (ab)using Oracle's datetime format models. TO_DATE(n, 'j') converts a number into a Julian day, the number of days since January 1, 4712 BC. TO_CHAR(<date>, 'jsp') converts this back into the integer (though as a string). The sp, is a format element suffix that spells the number. This'll actually work with quite a lot of numbers.
The &1 is a substitution variable that'll only work with clients that accept it, for instance SQL*Plus.
Python 2, 64
print' ottffssennwhoiieiieoruvxvgn ere ehe e nt'[input()::9]
This is what the string looks like with some extra whitespace (try reading vertically):
o t t f f s s e n
n w h o i i e i i
e o r u v x v g n
e r e e h e
e n t
As explained in the comments below, [input()::9] starts at the given index and selects every ninth subsequent character.
Tcl, 61
Number entered as command line argument
lindex {- one two three four five six seven eight nine} $argv
VBScript 98 80 75
msgbox split(" one two three four five six seven eight nine")(inputbox(""))
GolfScript, 51 bytes
~'
one
two
three
four
five
six
seven
eight
nine'n/=
It's a simple lookup table. The input is evaluated (~), an array of the values is created, and the index is found.