r/dailyprogrammer • • Mar 05 '12

[3/5/2012] Challenge #18 [easy]

Often times in commercials, phone numbers contain letters so that they're easy to remember (e.g. 1-800-VERIZON). Write a program that will convert a phone number that contains letters into a phone number with only numbers and the appropriate dash. Click here to learn more about the telephone keypad.

Example Execution: Input: 1-800-COMCAST Output: 1-800-266-2278

12 Upvotes

8 comments sorted by

3

u/bigmell Mar 05 '12

Perl

#!/usr/bin/perl -w
my $s = shift;
my %replace = (2=>"abc",3=>"def",4=>"ghi",5=>"jkl", 6=>"mno",7=>"pqrs",8=>"tuv",9=>"wxyz");
print "Original:$s ";
$s =~ s/[$replace{$_}]/$_/g for (keys %replace);
print "Replacement:$s\n";

2

u/prophile Mar 05 '12

Done in four lines of Python.

import string, sys
table = string.maketrans(string.ascii_letters, '22233344455566677778889999' * 2)
basic = sys.argv[1].translate(table, '-')
print '{0}-{1}-{2}-{3}'.format(basic[0], basic[1:4], basic[4:7], basic[7:])

0

u/[deleted] Mar 08 '12

[deleted] — view deleted comment

2

u/patrickgh3 Mar 09 '12

Here is my solution in Java: http://pastebin.com/91cfe9h0

Hopefully you can look at my solution and see how yours could be made more concise. I'm still a beginner though, so I may have made some mistakes. Also, though I can't explain it very well, the method by which I converted the inputted chars into their respective numbers took me a while to come up with, but it is more efficient. Cheers!