DEV Community

Edwin Torres
Edwin Torres

Posted on • Updated on

An Algorithm to Translate Vanity Phone Numbers

Background

How would you translate a vanity phone number like 1 800 RED CROSS to its actual phone number: 1-800-733-2767?

If you're dialing the number on a phone ☎️, you just find the letters on the keypad and press the corresponding numbers. However, writing a program to translate a vanity number requires an algorithm.

Data

The input data to this algorithm is a vanity phone number. It can take many forms:

1 800 RED CROSS
1-800-RED-CROSS
1-800-Red-Cross
1800REDCROS
1.800.RED.CROS
800-RED-cross
800REDCROS
Enter fullscreen mode Exit fullscreen mode

Assumptions

With the data in mind, let's make some basic assumptions about the algorithm:

  • The input data is a string.
  • The string must be at least 10 characters long, which is a 10-digit number without separators.
  • The string may include all valid characters.

Algorithm

There are many different ways to write this algorithm. But the basic approach is:

  1. Accept a vanity phone number as an input string.
  2. If the string length is less than 10, output an error message and quit the program.
  3. Convert the string to be all uppercase.
  4. For each character in the string:
  • If the character is in the range A-Z, translate it to its corresponding keypad number and output the number.
  • If the character is not in the range A-Z, output the character.

Java Implementation

Here are some tips for implementing this algorithm in Java ☕️:

  • The toUpperCase() function returns an uppercase version of a string.
  • The charAt() function accesses a specific character in a string.
  • A for loop can work nicely with charAt() to access each character of the string, in order.
  • One way to translate a letter from A-Z to its corresponding keypad number is to use a switch statement, where each case is a letter from A-Z.

There are many ways to implement an algorithm to translate vanity phone numbers to real phone numbers. The first step is to develop the algorithm itself. Consider the input data, assumptions, processing logic, and output. Developing the algorithm first makes coding the solution easier.

Now it’s your turn. Can you code the solution? 👩‍💻🧑‍💻

Thanks for reading.

Follow me on Twitter @realEdwinTorres for more programming tips. 😀

Top comments (1)

Collapse
 
aloisdg profile image
Aloïs de Gouvello • Edited

Here is a C# implementation for fun: dotnetfiddle.net/EVJI8t