47
\$\begingroup\$

Winner: professorfish's bash answer! An entire 9 bytes! Wow!

You may continue to submit your answer, however you can no longer win. Original post kept for posterity:


Your goal is to convert a whole number between 1-9 into the word it represents.

  • You will not need to worry about decimals
  • The user will input a number. Assume that they will never enter anything 10 or higher
  • The user must type the number at some point, however the method the program reads it does not matter. It can be with stdin, reading a text file, etc, however the user must press the 9 button on their keyboard (for example) at some point
  • It is not case sensitive (ie, "one", "One", "oNe", "OnE", etc are all acceptable)
  • HTTP/etc requests are allowed, however any code executed by the server the request is made to counts towards the byte count of your final code (e.g. if I had a C++ program make a HTTP request, the PHP code used in the HTTP request counts)
  • Anything that can compile and run is acceptable

  • This contest has ended on June 27th, 2014 (7 days from posting).
  • This is a , so the shortest code wins
\$\endgroup\$
  • 2
    \$\begingroup\$ Is trailing whitespace (i.e. one ) acceptable? \$\endgroup\$ – grc Jun 21 '14 at 5:13
  • 1
    \$\begingroup\$ @grc Yes, as long as the program outputs the word. \$\endgroup\$ – Jon Jun 21 '14 at 5:14
  • 1
    \$\begingroup\$ you should specify that only the given number may be printed and not the other numbers. \$\endgroup\$ – Pinna_be Jun 21 '14 at 7:04
  • 1
    \$\begingroup\$ @Pinna_be for example, if I input 3, you can't output one two three four five six seven eight nine even though you technically output three. Similarly, you can't output three seven, etc. \$\endgroup\$ – Jon Jun 21 '14 at 7:06
  • 1
    \$\begingroup\$ This question was quite nice. But I don't like the adding of the date limit. Especially, the date limit has been added just before the date limit, not 7 days before. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 18:12

70 Answers 70

19
\$\begingroup\$

Bash (with bsdgames), 9

number -l

Reads from standard input.

I don't know why there's a utility for this, but whatever.

\$\endgroup\$
  • 2
    \$\begingroup\$ I'm not sure I like installing bsdgames and then calling it "bash", though I'll admit that my reservation is subjective. \$\endgroup\$ – Paul Draper Jun 30 '14 at 4:43
  • \$\begingroup\$ @PaulDraper Neither do I. I didn't post this as a serious answer, I think one of the other answers deserved to be accepted \$\endgroup\$ – user16402 Jun 30 '14 at 8:21
  • 5
    \$\begingroup\$ Ain't this a standard loophole? \$\endgroup\$ – Justin Jul 2 '14 at 18:26
  • 2
    \$\begingroup\$ @Quincunx yes, it basically is. Although most things are external utilities in Bash, I wouldn't count the bsdgames package as something very permissible (unlike grep, wget, coreutils, sed, bc...). \$\endgroup\$ – user16402 Jul 3 '14 at 20:02
132
\$\begingroup\$

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.

\$\endgroup\$
  • 9
    \$\begingroup\$ Oh, shit, I like this. Probably worth pointing out that this is python 2, by the way. \$\endgroup\$ – undergroundmonorail Jun 21 '14 at 7:33
  • 3
    \$\begingroup\$ Explain please! :) \$\endgroup\$ – Christofer Ohlsson Jun 21 '14 at 10:12
  • 6
    \$\begingroup\$ @ChristoferOlsson input()::9 is a range from input() to the end of the string in steps of 9, like 1,10,19,28,37 or 3,12,21,30,39, which are exactly the indices at which the letters for the corresponding word are found. \$\endgroup\$ – Martin Ender Jun 21 '14 at 10:14
  • 1
    \$\begingroup\$ @m.buettner thanks! That's nice. \$\endgroup\$ – Christofer Ohlsson Jun 21 '14 at 10:18
  • 6
    \$\begingroup\$ Isn't this something like what a rail-fence cipher does? (+1 for a neat solution by the way.) \$\endgroup\$ – Lou Jun 21 '14 at 16:09
18
\$\begingroup\$

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))
\$\endgroup\$
  • 10
    \$\begingroup\$ Isn't this a standard loophole? \$\endgroup\$ – seequ Jun 21 '14 at 22:45
  • 2
    \$\begingroup\$ Loophole in what sense? It's clearly defined in Hyperspec: lispworks.com/documentation/lw50/CLHS/Body/22_cba.htm \$\endgroup\$ – filcab Jun 21 '14 at 22:48
  • 10
    \$\begingroup\$ As in this: meta.codegolf.stackexchange.com/a/1078/20356 \$\endgroup\$ – seequ Jun 21 '14 at 23:09
  • 3
    \$\begingroup\$ Whether it's a standard loophole or not, it's what I came here to post, too. +1 :) \$\endgroup\$ – Joshua Taylor Jun 21 '14 at 23:16
  • 5
    \$\begingroup\$ @TheRare Looking at the comments to that answer, I don't think there is strong community consensus that this is a loophole. My feeling is that questions need to explicitly ban use of this kind of built in function if they are not to be used. \$\endgroup\$ – Digital Trauma Jun 22 '14 at 2:52
16
\$\begingroup\$

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' a says, "Please print what's listed on line 'X' of file 'a'" sed is a Unix stream editor. -n means be silent, or only essentially ignore everything else. Xp means print what's on line 'X'.

\$\endgroup\$
  • 2
    \$\begingroup\$ Nice first answer! Thank you for taking the time to figure out how we format our answers on this site. Welcome to Programming Puzzles and Code Golf! \$\endgroup\$ – Justin Jun 21 '14 at 7:04
  • 2
    \$\begingroup\$ You didn't count the linefeeds in a. \$\endgroup\$ – Dennis Jun 21 '14 at 7:24
  • 1
    \$\begingroup\$ One byte less than before, accepts a command-line argument and doesn't require additional files: pastebin.com/qdbXKQGP Bash will complain about the missing heredoc delimiter, but it will run fine with Dash and Zsh. \$\endgroup\$ – Dennis Jun 21 '14 at 15:09
  • 1
    \$\begingroup\$ @Dennis oh cool I like it. Am I supposed to edit my answer with yours now? Sorry, am new to code golf. \$\endgroup\$ – Eric Lagergren Jun 21 '14 at 16:49
  • 1
    \$\begingroup\$ You can omit the ' quotes. You could also try using a here string instead of the external file. But you really should count the line breaks in your file. \$\endgroup\$ – Digital Trauma Jun 21 '14 at 17:29
16
\$\begingroup\$

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'.

Take a look at the Powershell version of this same trick

\$\endgroup\$
  • \$\begingroup\$ How does this work ? Let's say I enter 9. What does the program do then ? \$\endgroup\$ – Nicolas Barbulesco Jun 22 '14 at 10:00
  • \$\begingroup\$ What does this -48 do here ? \$\endgroup\$ – Nicolas Barbulesco Jun 22 '14 at 10:09
  • 2
    \$\begingroup\$ @NicolasBarbulesco added an How does this work? paragraph. Does it make sense? \$\endgroup\$ – rene Jun 22 '14 at 10:56
  • 1
    \$\begingroup\$ @NicolasBarbulesco - It's sorted alphabetically. Which makes sense in every context except "These words are numbers". Since I'm sure the documentation is automatically generated, it wouldn't make sense to special case the one article. \$\endgroup\$ – Bobson Jun 23 '14 at 18:35
13
\$\begingroup\$

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
\$\endgroup\$
  • 8
    \$\begingroup\$ @Dennis I can't see how that could be so hard. Simply take the file, turn it into a char[][], keep an x and y location, and execute the character at that location. The hardest thing would be defining the operation for every possible character. \$\endgroup\$ – Justin Jun 21 '14 at 6:07
  • 1
    \$\begingroup\$ You can easily save two bytes with a &1-. \$\endgroup\$ – har-wradim Jun 21 '14 at 19:42
10
\$\begingroup\$

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])
\$\endgroup\$
  • \$\begingroup\$ I tried something similar but couldn't figure out a valid base64 string starting with a number. I think you answer has been corrupted by stackexchange though. \$\endgroup\$ – nderscore Jun 21 '14 at 16:40
  • \$\begingroup\$ @nderscore, damn your'right. Amending the post, still it's valid according to me \$\endgroup\$ – edc65 Jun 21 '14 at 16:43
  • 1
    \$\begingroup\$ With the version that has the escaped characters, everything works but 3 and 8, the output Tree and EightF. \$\endgroup\$ – Justin Jun 21 '14 at 16:54
  • 3
    \$\begingroup\$ @Quincunx 'Tree' is me not speak english \$\endgroup\$ – edc65 Jun 21 '14 at 17:14
10
\$\begingroup\$

Javascript 73

alert('0one0two0three0four0five0six0seven0eight0nine'.split(0)[prompt()])

69

alert(btoa("ôéÞõ5õ1ëxO_¢êý|Þöȱõ'xß^hSôا{Ý").split(9)[prompt()])
\$\endgroup\$
  • \$\begingroup\$ Technically wouldn't alert('0one0two0three0four0five0six0seven0eight0nine'.split(0)[#]) be the same thing but save you 8 bytes? The user still inputs the number they want... \$\endgroup\$ – Eric Lagergren Jun 22 '14 at 19:32
  • \$\begingroup\$ @eric_lagergren do you mean the user would have to change the number in the source? I don't think that would count as input. \$\endgroup\$ – nderscore Jun 22 '14 at 23:45
  • \$\begingroup\$ Oh, okay, I see what you mean. I suppose if you ran it like a command in the console it'd be part of the input as opposed to the source. \$\endgroup\$ – Eric Lagergren Jun 22 '14 at 23:52
7
\$\begingroup\$

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).

\$\endgroup\$
  • 1
    \$\begingroup\$ Save a couple of characters: $_=(one,two,three,four,five,six,seven,eight,nine)[$_-1] \$\endgroup\$ – Zaid Jun 21 '14 at 18:30
  • 2
    \$\begingroup\$ @Zaid: Thanks, it saved two bytes. (I am to used to use strict). \$\endgroup\$ – Heiko Oberdiek Jun 21 '14 at 19:10
  • \$\begingroup\$ I don't like that "-1". $_=(nine,eight,seven,six,five,four,three,two,one)[-$_] - one character shorter. \$\endgroup\$ – aragaer Jun 23 '14 at 19:26
  • \$\begingroup\$ @aragaer: Thanks, nice idea. \$\endgroup\$ – Heiko Oberdiek Jun 23 '14 at 19:39
6
\$\begingroup\$

Oracle SQL - 46

select to_char(to_date(&1,'j'),'jsp')from dual

Demonstration

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.

\$\endgroup\$
  • \$\begingroup\$ I have a love/hate relationship with Oracle's RDBMS but this is nice. \$\endgroup\$ – rene Jun 24 '14 at 9:07
6
\$\begingroup\$

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=

Try it online.

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
\$\endgroup\$
  • \$\begingroup\$ Wow, our answers are identical, even in length (I assume the user inputs a string). \$\endgroup\$ – Justin Jun 21 '14 at 5:06
  • 1
    \$\begingroup\$ @Quincunx: Alike minds think great! :P But reading user input will cost two bytes in CJam, so I'll have to think of something else... \$\endgroup\$ – Dennis Jun 21 '14 at 5:20
  • \$\begingroup\$ @Quincunx: It should work with GolfScript as well, although it probably won't save bytes. Base64 dump: IgGMOPiMFVMfl3LyoDHzA0j82AhFLPGF8TQiMjU2YmFzZSAyMGJhc2V7MTAxK30lIiIr \$\endgroup\$ – Dennis Jun 21 '14 at 6:53
  • \$\begingroup\$ This is what I managed to come up with; it's longer: golfscript.apphb.com/… \$\endgroup\$ – Justin Jun 21 '14 at 7:10
  • \$\begingroup\$ Do you know what encoding golfscript expects for non-ascii characters? It seems to not be utf-8 \$\endgroup\$ – Justin Jun 21 '14 at 7:26
5
\$\begingroup\$

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.

Try it here

\$\endgroup\$
  • \$\begingroup\$ The user must input a string, you can't have it hard-coded. Also, your Try it here link has different code than the pasted code. \$\endgroup\$ – Jon Jun 21 '14 at 5:12
  • \$\begingroup\$ @Chipperyman The user does input a string in this program. The Try it here link's difference in code is because the webpage does not support user input. Change the string after the ;, this is identical to user input. \$\endgroup\$ – Justin Jun 21 '14 at 5:15
  • \$\begingroup\$ Ah, I see. I don't know golfscript very well, thanks for letting me know. \$\endgroup\$ – Jon Jun 21 '14 at 5:15
  • 2
    \$\begingroup\$ @Chipperyman: GolfScript places the contents of STDIN on the stack before executing the script itself. \$\endgroup\$ – Dennis Jun 21 '14 at 5:18
  • 2
    \$\begingroup\$ Hah! I can beat you by one byte! ;-) \$\endgroup\$ – Ilmari Karonen Jun 25 '14 at 10:09
4
\$\begingroup\$

Perl, 60 bytes

$_=(ZOneTwoThreeFourFiveSixSevenEightNine=~/.[a-z]*/g)[$_]

Requires the -p switch (two bytes).

Example

$ perl -p convert.pl <<< 5
Five

How it works

  • -p reads from STDIN and saves the result in $_.

  • =~/.[a-z]*/g splits 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 $_.

  • -p prints the value of $_.

\$\endgroup\$
  • 2
    \$\begingroup\$ I like the regex trick. +1 \$\endgroup\$ – seequ Jun 21 '14 at 15:56
3
\$\begingroup\$

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

\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
3
\$\begingroup\$

(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]}
\$\endgroup\$
  • 2
    \$\begingroup\$ Same character count: v=(one two three four five six seven eight nine) and echo ${v[$1-1]} \$\endgroup\$ – Dennis Williamson Jun 22 '14 at 4:52
3
\$\begingroup\$

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()]
\$\endgroup\$
  • \$\begingroup\$ This one is nice too. :-) It works. \$\endgroup\$ – Nicolas Barbulesco Jun 22 '14 at 9:55
  • 3
    \$\begingroup\$ You can save one character like this: 'nine eight seven six five four three two one'.split()[-input()] \$\endgroup\$ – flornquake Jun 22 '14 at 23:01
  • \$\begingroup\$ Thats a Nice one ! \$\endgroup\$ – Willem Jun 23 '14 at 17:18
3
\$\begingroup\$

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]);
    }}
\$\endgroup\$
3
\$\begingroup\$

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!

\$\endgroup\$
  • 1
    \$\begingroup\$ +1 Code-golfers generally don't mind if your c code compiles with warnings, as long as it meets the specs. So you can omit the #include and main()'s return type. Also a bit of refactoring of your expression: main(){printf("%.5s","one two threefour five six seveneightnine"+5*getchar()-245);}. 86 chars by my count. \$\endgroup\$ – Digital Trauma Jun 24 '14 at 15:51
  • \$\begingroup\$ I don't get the length stuff, and I don't see where there would be 7 chars. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 18:06
  • \$\begingroup\$ @NicolasBarbulesco: It's 111 characters--but if we treat the 111 as binary, that would convert to 7 in decimal. \$\endgroup\$ – Jerry Coffin Jun 26 '14 at 18:13
  • \$\begingroup\$ Jerry, there is code golf running in your head ! \$\endgroup\$ – Nicolas Barbulesco Jul 8 '14 at 10:29
3
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ shouldn't be 5? \$\endgroup\$ – rpax Jun 23 '14 at 14:13
  • \$\begingroup\$ @rpax I don't believe the input is counted as a character, is it? \$\endgroup\$ – CousinCocaine Jun 24 '14 at 12:58
  • 1
    \$\begingroup\$ This is clever. But this misses the input. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 17:45
  • 1
    \$\begingroup\$ Unfortunately this is not a valid answer because: It never accepts input from the user AND it only works if the number is 4. \$\endgroup\$ – Jon Jun 27 '14 at 7:10
  • 1
    \$\begingroup\$ The comment by Chipperyman on this answer by CousinCocaine is true. But it is true for the answer by @RegisteredUser too. However, Chipperyman has rejected this answer by CousinCocaine, and has declared the answer by Registered User winner ex æquo. In addition, the answer by Registered User is a replica of this answer by CousinCocaine. This is more than unfair. \$\endgroup\$ – Nicolas Barbulesco Jun 28 '14 at 16:42
2
\$\begingroup\$

VBScript 98 80 75

msgbox split(" one two three four five six seven eight nine")(inputbox(""))
\$\endgroup\$
2
\$\begingroup\$

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

\$\endgroup\$
  • \$\begingroup\$ You can save one char by writing it as a train ((;:'one two blah')>@{~<:) and another six by using the gerund one`two`blah instead of ;:. \$\endgroup\$ – algorithmshark Jun 21 '14 at 16:57
  • \$\begingroup\$ @algorithmshark Thanks! I'm still learning J. Although, wouldn't the train version require the text to be infinite rank (edit: apparently not... why not?) and the gerund version extra quotes (edit: oh, it creates a list of boxes)? \$\endgroup\$ – seequ Jun 21 '14 at 17:07
  • \$\begingroup\$ A fork can have a noun in the left argument, which is shorthand for a constant verb producing that noun with infinite rank (q.v. the Dictionary). And no, no extra quotes on the gerund: undefined names are treated as references to verbs, and the gerund for that is just a boxed string containing the name. \$\endgroup\$ – algorithmshark Jun 21 '14 at 17:22
  • \$\begingroup\$ Also, you don't have to write the STDIN version as a verb expression: >one`two`three`four`five`six`seven`eight`nine{~<:".1!:1]1 is 3 chars shorter. \$\endgroup\$ – algorithmshark Jun 21 '14 at 17:35
  • 1
    \$\begingroup\$ @algorithmshark Haha, why didn't I do it that way? \$\endgroup\$ – seequ Jun 21 '14 at 18:02
2
\$\begingroup\$

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]
\$\endgroup\$
  • \$\begingroup\$ Your first script does not work, on my Mac. Can't locate Number/Spell.pm in @INC (@INC contains: /Library/Perl/5.16/darwin-thread-multi-2level /Library/Perl/5.16 /Network/Library/Perl/5.16/darwin-thread-multi-2level /Network/Library/Perl/5.16 /Library/Perl/Updates/5.16.2 /System/Library/Perl/5.16/darwin-thread-multi-2level /System/Library/Perl/5.16 /System/Library/Perl/Extras/5.16/darwin-thread-multi-2level /System/Library/Perl/Extras/5.16 .) at toto.pl line 1. BEGIN failed--compilation aborted at toto.pl line 1. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 17:59
  • \$\begingroup\$ Your second script does not work, on my Mac. syntax error at titi.pl line 1, near "say qw(one two three four five six seven eight nine)" Execution of titi.pl aborted due to compilation errors. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 18:01
2
\$\begingroup\$

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 ! ]

\$\endgroup\$
  • 1
    \$\begingroup\$ set n to text returned of ... Wow. \$\endgroup\$ – seequ Jun 22 '14 at 17:27
2
\$\begingroup\$

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

\$\endgroup\$
2
\$\begingroup\$

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.

\$\endgroup\$
  • 1
    \$\begingroup\$ Please add a comment if downvoting. \$\endgroup\$ – aditsu Jun 22 '14 at 12:45
  • \$\begingroup\$ -1, this is a standard loophole. \$\endgroup\$ – nyuszika7h Jun 22 '14 at 21:58
  • 3
    \$\begingroup\$ @nyuszika7h it's specifically allowed in this question \$\endgroup\$ – aditsu Jun 23 '14 at 2:46
  • 1
    \$\begingroup\$ Sorry, I missed that. I can't undo my downvote now until the answer is edited. \$\endgroup\$ – nyuszika7h Jun 23 '14 at 9:34
  • 1
    \$\begingroup\$ @nyuszika7h edited \$\endgroup\$ – aditsu Jun 23 '14 at 10:26
2
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

Ruby 64

p %w?one two three four five six seven eight nine?[$*[0].to_i-1]
\$\endgroup\$
  • 1
    \$\begingroup\$ You can chop few more bytes by substituting 9 directly at the place of x \$\endgroup\$ – Mr. Alien Jun 21 '14 at 9:38
  • 6
    \$\begingroup\$ I don't see where this code takes in input. And why write 9-1 when you can just say 8? Of course both 9-1 and 8 are wrong; this script outputs "nine" all the time and ignores input. \$\endgroup\$ – Ray Toal Jun 21 '14 at 22:27
2
\$\begingroup\$

BASH 9

shameless Linux-replica of cousincoicane's answer

spd-say 1

speaks out one

\$\endgroup\$
  • 1
    \$\begingroup\$ Wouldn't this only work if the input was 1? \$\endgroup\$ – Jon Jun 25 '14 at 4:38
  • 1
    \$\begingroup\$ @Chipperyman it works for any number \$\endgroup\$ – Registered User Jun 25 '14 at 4:38
  • \$\begingroup\$ Limit, but clever ! \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 17:27
  • \$\begingroup\$ This misses the input. \$\endgroup\$ – Nicolas Barbulesco Jun 26 '14 at 17:32
  • \$\begingroup\$ @nicolasbarbulesco yes. but there were many other answers that miss input, so I went ahead with this. \$\endgroup\$ – Registered User Jun 27 '14 at 2:39
2
\$\begingroup\$

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
\$\endgroup\$

protected by Doorknob Jun 23 '14 at 19:41

Thank you for your interest in this question. Because it has attracted low-quality or spam answers that had to be removed, posting an answer now requires 10 reputation on this site (the association bonus does not count).

Would you like to answer one of these unanswered questions instead?

Not the answer you're looking for? Browse other questions tagged or ask your own question.