Thursday, September 17, 2015

Telephone letter mapping

Problem: 

Given a number from the digits of a phone dialpad, output the letter permutations it could form, using the letters on the dialpad for that each digit given.

Note: This was an assignment for Chapter 7, CS265 Cryptography and Information Security class at San Jose State University.

Solution:

import java.util.ArrayList;

public class NumLetter {
 String[] letters = new String[10];
 
 void prepopulate(){
  NumLetter[] a = new NumLetter[5];
  letters[0] = "";
  letters[1] = "";
  letters[2] = "ABC";
  letters[3] = "DEF";
  letters[4] = "GHI";
  letters[5] = "JKL";
  letters[6] = "MNO";
  letters[7] = "PQRS";
  letters[8] = "TUV";
  letters[9] = "WXYZ";  
  System.out.println(letters);
 }
 
 private void findPermutations(int n) {

  int digitCnt = 0, temp = n;
  while(temp != 0){
   temp/=10;
   digitCnt++;
  }
  if(digitCnt == 0) return;
  
  int maxDigits = digitCnt;
  
  ArrayList result = new ArrayList();
  String chars = letters[(int) (n/Math.pow(10, digitCnt-1))];
  n = (int) (n % Math.pow(10, digitCnt-1));digitCnt--;
  for(int j = 0; j< chars.length(); j++){
   result.add(chars.charAt(j) + "");
  }
  
  for(int i=1; i< maxDigits; i++)
  {
   chars = letters[(int) (n/Math.pow(10, digitCnt-1))];
   ArrayList tempRes = new ArrayList();
   for(int j = 0; j< chars.length(); j++)
   {
    for(int k = 0; k< result.size(); k++)
    {
     tempRes.add(result.get(k) + chars.charAt(j));
    }
   }
   result = tempRes;
   n = (int) (n % Math.pow(10, digitCnt-1));digitCnt--;
  }
  System.out.println(result);
 }
 
 public static void main(String[] args) {
  NumLetter ob = new NumLetter();
  ob.prepopulate();
  ob.findPermutations(5465);
 }
}

Example

Input: 5465
Output: 
[JGMJ, KGMJ, LGMJ, JHMJ, KHMJ, LHMJ, JIMJ, KIMJ, LIMJ, JGNJ, KGNJ, LGNJ, JHNJ, KHNJ, LHNJ, JINJ, KINJ, LINJ, JGOJ, KGOJ, LGOJ, JHOJ, KHOJ, LHOJ, JIOJ, KIOJ, LIOJ, JGMK, KGMK, LGMK, JHMK, KHMK, LHMK, JIMK, KIMK, LIMK, JGNK, KGNK, LGNK, JHNK, KHNK, LHNK, JINK, KINK, LINK, JGOK, KGOK, LGOK, JHOK, KHOK, LHOK, JIOK, KIOK, LIOK, JGML, KGML, LGML, JHML, KHML, LHML, JIML, KIML, LIML, JGNL, KGNL, LGNL, JHNL, KHNL, LHNL, JINL, KINL, LINL, JGOL, KGOL, LGOL, JHOL, KHOL, LHOL, JIOL, KIOL, LIOL]

No comments:

Post a Comment