Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. Join them; it only takes a minute:

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top


You are making a new phone where people can type in specialized phone numbers, for example, 1-800-program, and they would be converted automatically to a usable phone number, like 1-800-7764726 (for the previous example).

Your program will recieve a string if any length with numbers, letters and dashes, and convert all the letters to their corresponding numbers.

Here is a keypad, for reference:



  • Your program will receive a string
  • It will process it and return/print another string
  • Any language is accepted
  • Since it is , the shortest code wins
share|improve this question
Should the program handle both upper and lower case letters in the input? – mattnewport Feb 19 '14 at 0:38
@mattnewport - no, assume the variable has been turned into lowercase already – TheDoctor Feb 19 '14 at 3:36

31 Answers 31

up vote 7 down vote accepted

GolfScript, 24 chars


Test input:


Test output:



  • { }% applies the code between the braces to each character of the input.

  • .96>{ }* executes the code between the inner braces if and only if the ASCII code of the character is greater than 96 (i.e. it is a lowercase letter).

  • The first , turns the character into a list of all characters with lower ASCII codes, and 91,'qx'+- filters out all characters with ASCII codes less than 91, as well as the letters q and x, from the list. Thus, for example, the character a gets turned into the 6-character list [\]^_`, while z gets turned into the 29-character list [\]^_`abcdefghijklmnoprstuvwy.

  • The second , counts the elements remaining in the list, and 3/ divides this count by three (rounding down). Finally, the ` turns the resulting number (in the range 2 – 9) into a string.

Thus, as per spec, hyphens and numbers are left unchanged, while lowercase letters are mapped into numbers according to the reference keypad diagram. The code will actually cleanly pass through all printable ASCII characters except for lowercase letters (which as mapped as described) and the characters {, | and } (which are mapped to the two-character string 10). Non-ASCII 8-bit input will produce all sorts of weird numeric output.

After all this, it's a bit disappointing that this only beats the trivial bash solution by just six chars.

share|improve this answer

Bash, 30

Edit: Thank you Doorknob for eliminating 3 chars

tr a-z 22233344455566677778889


share|improve this answer
Can't you remove the last 3 9s? – Doorknob Feb 19 '14 at 1:01

C, 83 78 77 65 63 62


share|improve this answer
Nice math. Just wanna say that you can reduce 1 char by assuming EOF is -1 and do ~(c=getchar()) – ace Feb 19 '14 at 8:31
Thanks, down to 62 with that tip! – mattnewport Feb 19 '14 at 8:33
Couldn't you use getch() instead of getchar()? – starsplusplus Feb 19 '14 at 10:15
Strictly speaking, getch() isn't standard C, as a result I guess it doesn't link in ideone. I tested it in MSVC anyway though and it doesn't really work sadly - as it directly consumes keyboard input there's no way to exit the program, although it does translate what you type on the fly which is kind of neat. – mattnewport Feb 19 '14 at 16:05

Javascript - 103 characters

alert(prompt().replace(/[a-z]/g,function(y){y=y.charCodeAt(0)-91;return y>27?9:y>24?8:y>20?7:~~(y/3)}))
share|improve this answer
I didn't know you could do that with .replace. Up vote for you! – SuperJedi224 Jun 11 '15 at 21:56

Ruby, 75 chars


Uses the deprecated chars with block, and prints each letter individually with $><<. I also like [[*?a..?z].index(c)||-1]; it grabs the character corresponding to that letter of the alphabet if it's a letter, and the last character (which happens to be the test character unchanged) if not.

Ruby, 43 (or 35) chars

Blatantly stealing from @ace ;)


Shave off 8 chars if I can run in IRB with the variable s as the string:'a-z','22233344455566677778889'
share|improve this answer

C++ - 222 chars

Longest solution so far:

#define o std::cout<<
int main(){std::string s;std::cin>>s;for(int i=0;i<s.size();i++){int j=s[i]-97;if(j<0)o s[i];if(0<=j&j<15)o 2+j/3;if(14<j&j<19)o 7;if(18<j&j<22)o 8;if(21<j&j<26)o 9;}}
share|improve this answer
Lol, I don't think longest solution is the goal here... – Danny Feb 19 '14 at 14:36
@Danny C++ does not lend itself well to code-golf. Java and C# are the only languages that are worse, that I know of (all the classes, object creation, and long names for output...). – Hosch250 Feb 19 '14 at 15:53
I know, I just thought it was funny that you mentioned "Longest solution". – Danny Feb 19 '14 at 15:55

Frink, 92

A rather verbose language, I know. This checks 8 values instead of 26 without having to type out the compares. Can any of the above "222333444.." solutions be reduced in a similar way?

Using built in structures, 107

co=new OrderedList

Using a custom recursive function, 92

share|improve this answer
+1 for reducing the string-translation method to an 8-character search. Nice touch. – Jonathan Van Matre Feb 25 '14 at 1:23

Smalltalk, 79 70

input is s:

s collect:[:c|' 22233344455566677778889999'at:1put:c;at:(($ato:$z)indexOf:c)+1]

probably not a candidate for being shortest - but may be of interest for an old trick to avoid a test for a not-found condition (indexOf: returns 0 in this case). So no special test for letters is needed. Some Smalltalks however, have immutable strings, and we need 4 more chars ("copy").

Oh, a better version, which even deals with immutable strings in 70 chars:

s collect:[:c|c,'22233344455566677778889999'at:(($ato:$z)indexOf:c)+1]
share|improve this answer

Mathematica 90

This follows the logic of @ace's solution:





share|improve this answer
Your arrow character representation isn't accepted by Mma in a copy/paste – Dr. belisarius Feb 19 '14 at 3:18
Also,you don't need the 1 in #1:) – Dr. belisarius Feb 19 '14 at 3:19
Belisarius, I changed the arrow back and removed the 1. Still 90 char but cut and paste will work. You understand of course the motivation to use the single char arrow. – DavidC Feb 19 '14 at 10:36
Been there, done that :) – Dr. belisarius Feb 19 '14 at 14:06

Perl, 50

Another obvious copy of Ace's bash answer

share|improve this answer
This code is working correctly but there's room for improvement. Let's get rid of $ARGV[0] and use -p switch instead which lets you nicely go through each line of stdin. While we're at it, the range in y/// doesn't need to be put in square brackets. We can also get rid of three 9's leaving just one and remove the final semi-colon: -p y/a-z/22233344455566677778889/ There you go, 30 + 1 for -p. Thank you for using Enterprise Chinese Perl Golfing and Optimization Services and have a nice day. – chinese perl goth Feb 19 '14 at 14:11

R, very long but fun

foo <- '1-800-splurghazquieaobuer57'
oof <- unlist(strsplit(foo,''))
#don't count that part - it's input formatting :-) 
digout <- unlist(strsplit('22233344455566677778889999','')) 
oof[oof%in%letters[1:26]] <- unlist(sapply(oof[oof%in%letters[1:26]], function(j) digout[which(letters[1:26]==j)] ))
share|improve this answer

k [32 Chars]

{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}


{(.Q.a!|,/(4 3 4,5#3)#'|$2+!8)x}"stack exchange"
"78225 39242643"
share|improve this answer

JavaScript, 85

JavaScript is never going to win the golf wars, but I like it and I wanted to do something different than jump on the @ace bandwagon.

alert(prompt().replace(/[a-z]/g,function(a){for(i=7;a<"dgjmptw{"[i--];);return i+4}))
share|improve this answer

PHP, 141

Not the shortest, but more fun:

<?php foreach(str_split($argv[1])as$c){$v=ord($c);if($v>114){$v--;}if($v==121){$v--;}if($v<123&$v>96){echo chr(ceil($v/3+17));}else{echo$c;}}

More readable:

foreach (str_split($argv[1]) as $c) {
  if ($v>114) {$v--;}
  if ($v==121){$v--;}
  if ($v<123 & $v>96){
    echo chr(ceil($v/3+17));
    } else {echo $c;}
share|improve this answer
OP said that the input is already in lowercase, so you can remove the strtolower – Einacio Feb 20 '14 at 19:00
Thanks, hadn't seen that change, updated now. – Rob Hoare Feb 20 '14 at 20:16

Python 2.7, 80

for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

I am new to python, so I'm sure there must be a way to golf this even further, it's a different aproach, hope you guys like it, my god, is python pretty!

Run example:

  • input: 01-800-abcdefghijklmnopqrstuvwxyz
  • output: 01-800-22233344455566677778889999
share|improve this answer

T-SQL, 216 bytes

I spent quite some time over the past couple of nights painstakingly creating a mathematical sequence function that would round correctly to generate the proper ASCII codes for the numbers from the alphabetical ASCII codes. It had a ridiculous number of decimal places in the coefficients, but it worked.

However, mattnewport's rational approach works in SQL as well, at a much lower cost of bytes, so I am shamelessly scrapping my own math in favor of his. Go up-vote him, it's an elegant solution!

Here's mine:


This uses a recursive CTE to make an impromptu stack of the characters in the phone number and translate the letters on the fly, then a bit of SQL trickery (SELECT @p=@p+columnValue) to recompose the string from the CTE without requiring another recursion construct.


DECLARE @s VARCHAR(MAX)='1-800-abcdefghijklmnopqrstuvwxyz'
--above code runs here
share|improve this answer

Python 2.7, 66 65

Anakata's Original

for c in raw_input():print'\b'+(`(ord(c)-97)/3+2-(c in('svyz'))`if c>'`'else c),

Further golfed

for c in input():print(ord(c)-91)/3-(c in('svyz'))if c>'`'else c,

I don't have enough reputation to comment on @anakata's answer, so I made a separate post here. I had the same idea (taking the ordinance modulus 3) but couldn't figure out how to print the right numbers for s - z.

Anyways, the golf improvements I made:

  • changed raw_input to input

  • removed the extraneous '\b' and parentheses and single quotes

  • removed the +2 offset and placed that in the original subtraction (97 - (3 * 2) = 91)

Tested with the Python 2.7.6 interpreter. Assumes, per the rules, a string input.

share|improve this answer
you could also remove the space between the ) and the if – Willem Mar 13 '14 at 18:57
You're right. good catch willem – zheshishei Mar 14 '14 at 17:24

PHP, 87

echo str_ireplace(range('a','z'),str_split('22233344455566677778889999'),fgets(STDIN));
share|improve this answer

q [38 Chars]


Inspired by @ace's solution


{(.Q.a!"22233344455566677778889999")x}"stack exchange"
"78225 39242643"
share|improve this answer

XQuery, 71

BaseX was used as XQuery processor. $i is input.


Not the shortest answer, but quite short and very readable.

share|improve this answer

Python, very ungolfed

Since everyone is copying ace, i decided to post the code i made up before i submitted the question:

def phonekeypad(text):
    c = ['','','abc','def','ghi','jkl','mno','pqrs','tuv','wxyz']
    st = ""
    for i in list(text):
        a = False
        for t in range(len(c)):
            if i in c[t]:
                st += str(t)
        if a == False:
            st += str(i)
    return st
share|improve this answer

EcmaScript 6 (103 bytes):


Expects i to contain the string.

Try it in any recent version of Firefox. I've not tried Google Chrome.

share|improve this answer

Python 3, 121

print("".join((lambda x:"22233344455566677778889999"[ord(x)-97] if ord(x)>96 and ord(x)<123 else x)(i) for i in input()))
share|improve this answer

Haskell, 93C

t[]_ a=a
 |True=t c e a


y "1-800-program"
share|improve this answer

C# 140

using System.Linq;class P{static void Main(string[]a){System.Console.Write(string.Concat(a[0].Select(d=>(char)(d>96?20-d/122+5*d/16:d))));}}
share|improve this answer


import string          
trans = str.maketrans(string.ascii_lowercase,
share|improve this answer

ECMASCRIPT, 101 (with input)

return "22233344455566677778889999"[c.charCodeAt(0)-65]||c})

Newline added for clarity. 85 characters if the input is in a variable.

share|improve this answer

Perl, 54

print map{/[a-y]/?int(5/16*ord)-28:/z/?9:$_}<>=~/./gs

Shoot, @RobHoare still beat me by 4 characters. :)

share|improve this answer

QBasic, 155

Ah, the memories...

FOR i=1 TO LEN(n$)
IF 97>a THEN
PRINT STR$(a\3.2-28);

This should have been shorter, but I was testing with, which doesn't allow single-line IF statements and behaves strangely if you leave the variable off of NEXT i. It also doesn't recognize the ASC function, so to run the code you'll need to add this workaround at the beginning:

FOR j=1 TO 255
IF CHR$(j)=LEFT$(s$,1) THEN

(The second time you run it, the interpreter will complain unless you remove the DECLARE FUNCTION line, go figure.)

share|improve this answer

R, 110



> s=strsplit(scan(,""),"")[[1]];i=grep("[a-z]",s);s[i]=sort(c(1:24%%8+2,7,9))[match(s[i],letters)];cat(s,sep="")
1: 1-800-program
Read 1 item
share|improve this answer

Your Answer


By posting your answer, you agree to the privacy policy and terms of service.

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