Epic Systems Interview Question
Java DevelopersCountry: United States
Interview Type: Written Test
Simple and efficient approach but doen't work for inputs like 567#76534#453
I have made some changes
String[] inputArray = input.split("#"); // 444 55566688833 999666888
Map<Character,List<Character>> numPad = new HashMap<Character, List<Character>>();
numPad.put('2', Arrays.asList( 'A', 'B', 'C' ) );
numPad.put('3', Arrays.asList( 'D', 'E', 'F' ) );
numPad.put('4', Arrays.asList( 'G', 'H', 'I' ) );
numPad.put('5', Arrays.asList( 'J', 'K', 'L' ) );
numPad.put('6', Arrays.asList( 'M', 'N', 'O' ) );
numPad.put('7', Arrays.asList( 'P', 'Q', 'R', 'S' ) );
numPad.put('8', Arrays.asList( 'T', 'U', 'V' ) );
numPad.put('9', Arrays.asList( 'W','X', 'Y', 'Z' ) );
StringBuffer buffer = new StringBuffer();
for (String element : inputArray) {
char previous=element.charAt(0);
int count = 0;
int len = element.length()-1;
for(int i=0;i<element.length();i++)
{
char current = element.charAt(i);
if(current == previous)
{
count++;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}else
{
count = 1;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}
previous = current;
}
buffer.append(" ");
}
System.out.println(buffer.toString());
return buffer.toString();
}
}
Just in case any once wants to have implementation in C
#include <stdio.h>
#include <string.h>
int findCurrentCharLen(char str[], int currentPos, int maxAllowed) {
int length = 0;
char currentChar = str[currentPos];
while(str[currentPos] == currentChar && length <= maxAllowed) {
length = length + 1;
currentPos = currentPos + 1;
}
return length;
}
int main() {
static char *hashMap[] = {"000","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ"};
char *str;
printf("Enter String: \n");
scanf("%s",str);
printf("Started Processing\n");
int length = strlen(str);
int processed = 0;
while(processed < length){
int intProcessing = str[processed] - '0';
if(intProcessing >=0 && intProcessing<= 9) {
int lenForChar = findCurrentCharLen(str, processed, strlen(hashMap[intProcessing-1]));
printf("%c",hashMap[intProcessing-1][lenForChar - 1]);
processed += lenForChar;
continue;
}
printf(" ");
processed += 1;
}
printf("\n\n");
}
[[[
private static String transate(String seq) {
char[][] dic = { { 'a', 'b', 'c' }, { 'd', 'e', 'f' },
{ 'g', 'h', 'i' }, { 'j', 'k', 'l' }, { 'm', 'n', 'o' },
{ 'p', 'q', 'r', 's' }, { 't', 'u', 'v' },
{ 'w', 'x', 'y', 'z' } };
String res = "";
for (int i = 0; i < seq.length(); i++) {
if (seq.charAt(i) == '#') {
res += ' ';
} else if (seq.charAt(i) >= '0' && seq.charAt(i) <= '9') {
char last = seq.charAt(i);
int index = (last - '0') - 2;
int c = 0;
while (++i < seq.length() && seq.charAt(i) == last)
c = (c + 1) % dic[index].length;
res += dic[index][c];
}
}
return res;
}
]]]
public enum NumbersToChar {
A("2"), B("22"), C("222"), D("3"), E("33"), F("333"); // and so on......
private String digits;
NumbersToChar(String digits) {
this.digits = digits;
}
String getDigits() {
return digits;
}
static void getCharactersAndSpaces(String b) {
StringBuilder sb = new StringBuilder();
int i = 0;
for (NumbersToChar ntc : NumbersToChar.values()) {
if (b.contains("#") && ntc.getDigits().equals(b.substring(i, b.indexOf('#')))) {
sb.append(ntc.name() + " ");
i = b.indexOf('#') + 1;
b = b.substring(i, b.length() - 1);
} else {
if (ntc.getDigits().equals(b))
sb.append(ntc.name());
}
}
System.out.println(sb);
}
public static void main(String[] args) {
NumbersToChar.getCharactersAndSpaces("2#33#");
}
}
import java.util.HashMap;
class ConvertMobileNumberIntoNumber {
public String solution(String str) {
HashMap<String, String> numToStrMap = new HashMap<String, String>();
numToStrMap.put("2", "ABC");
numToStrMap.put("3", "DEF");
numToStrMap.put("4", "GHI");
numToStrMap.put("5", "JKL");
numToStrMap.put("6", "MNO");
numToStrMap.put("7", "PQRS");
numToStrMap.put("8", "TUV");
numToStrMap.put("9", "WXYZ");
String[] arr = str.split("#");
String out = "";
for (int i = 0; i < arr.length - 1; i++) {
out = out + numToStrMap.get("" + arr[i].charAt(0)).charAt(arr[i].length() - 1) + " ";
}
out = out + numToStrMap.get("" + arr[arr.length - 1].charAt(0)).charAt(
arr[arr.length - 1].length() - 1);
return out;
}
}
public class EpicConvertMobileNumberIntoNumber {
public static void main(String[] args) {
ConvertMobileNumberIntoNumber mSol = new ConvertMobileNumberIntoNumber();
System.out.println(mSol.solution("22#22"));
}
}
std::string ConvertNumberToCharacter( char* s ) {
std::string res;
int i = 0, j = 0;
while( s[i] != '\0' ){
int k = 1;
while( s[i] == s[i+k] ){
k++;
}
if ( (int)s[i] > (int)'7')
res.push_back( (char)((int)'a' + ((int)s[i] - (int)'2') * 3 + k ));
else
res.push_back( (char)((int)'a' + ((int)s[i] - (int)'2') * 3 + k - 1));
i += k;
}
return res;
}
public class StringT9 {
public static void main(String args[]){
//String input="22233#23";
String input="2#22#44#444#7777#44#33#55#8";
char[] in=input.toCharArray();
char prev,curr = 0;
prev=in[0];
int count=0;
//to find change in sequence
for(char i:in){
curr=i;
if(curr==prev)
{
count++;
prev=curr;
}
else
{
printChar(prev,count);//if prev is not same as curr,
// call helper function with current count
count=1;
prev=curr;
}
}
if(prev==curr)//corner case
{
printChar(prev,count);
}
}
private static void printChar(char prev, int count) {
//to handle space
if(prev=='#')
{
System.out.print(" ");
return;
}
if((prev=='8'))//special case of 4 char in 7 and 9
{
int b=Character.getNumericValue(prev);
char a= (char) ((66+((b-2)*3))+count-1);
System.out.print(a);
return;
}
//normal key presse
int b=Character.getNumericValue(prev);
char a= (char) ((65+((b-2)*3))+count-1);
System.out.print(a);
}
}
i tried with ASCII values
class PhoneKeypad
{
static void Main(String[] args)
{
char[] inputs = Console.ReadLine().ToCharArray();
for (int i = 0; i < inputs.Length; i++)
{
int position = Convert.ToInt32(inputs[i]);
if (position == 48 || position == 49 || position == 35 || position == 42)
{
Console.Write(inputs[i]);
}
else
if (position >= 50 && position <= 57)
{
int num = Convert.ToInt32(Convert.ToString(inputs[i]));
i += 1;
int strokes = Convert.ToInt32(Convert.ToString(inputs[i]));
char outChar = Convert.ToChar((((num - 2) * 3) + 65) + strokes-1);
Console.Write(outChar);
}
}
Console.ReadKey();
}
}
class PhoneKeypad
{
static void Main(String[] args)
{
char[] inputs = Console.ReadLine().ToCharArray();
for (int i = 0; i < inputs.Length; i++)
{
int position = Convert.ToInt32(inputs[i]);
if (position == 48 || position == 49 || position == 35 || position == 42)
{
Console.Write(inputs[i]);
}
else
if (position >= 50 && position <= 57)
{
int num = Convert.ToInt32(Convert.ToString(inputs[i]));
i += 1;
int strokes = Convert.ToInt32(Convert.ToString(inputs[i]));
char outChar = Convert.ToChar((((num - 2) * 3) + 65) + strokes-1);
Console.Write(outChar);
}
}
Console.ReadKey();
}
}
class PhoneKeypad
{
static void Main(String[] args)
{
char[] inputs = Console.ReadLine().ToCharArray();
for (int i = 0; i < inputs.Length; i++)
{
int position = Convert.ToInt32(inputs[i]);
if (position == 48 || position == 49 || position == 35 || position == 42)
{
Console.Write(inputs[i]);
}
else
if (position >= 50 && position <= 57)
{
int num = Convert.ToInt32(Convert.ToString(inputs[i]));
i += 1;
int strokes = Convert.ToInt32(Convert.ToString(inputs[i]));
char outChar = Convert.ToChar((((num - 2) * 3) + 65) + strokes-1);
Console.Write(outChar);
}
}
Console.ReadKey();
}
}
public class NumberToCharPhone2{
public static void main(String[] args){
String sentence="44,444#446669#277733#99966688";
String sentv=sentence+",";
System.out.print("\n \n \t \t \t \" ");
for(int i=0;i<sentv.length();i++){
char num=sentv.charAt(i);
int next1=i+1;
int next2=next1+1;
int next3= next2+1;
switch (num){
case '2': if(sentv.charAt(next1)=='2'){
i++;
if(sentv.charAt(next2)=='2'){
i++;
System.out.print("c");
break;
}
System.out.print("b");
break;
}
System.out.print("a");
break;
case '3': if(sentv.charAt(next1)=='3'){
i++;
if(sentv.charAt(next2)=='3'){
i++;
System.out.print("f");
break;
}
System.out.print("e");
break;
}
System.out.print("d");
break;
case '4': if(sentv.charAt(next1)=='4'){
i++;
if(sentv.charAt(next2)=='4'){
i++;
System.out.print("i");
break;
}
System.out.print("h");
break;
}
System.out.print("g");
break;
case '5': if(sentv.charAt(next1)=='5'){
i++;
if(sentv.charAt(next2)=='5'){
i++;
System.out.print("l");
break;
}
System.out.print("k");
break;
}
System.out.print("j");
break;
case '6': if(sentv.charAt(next1)=='6'){
i++;
if(sentv.charAt(next2)=='6'){
i++;
System.out.print("o");
break;
}
System.out.print("n");
break;
}
System.out.print("m");
break;
case '7': if(sentv.charAt(next1)=='7'){
i++;
if(sentv.charAt(next2)=='7'){
i++;
if(sentv.charAt(next3)=='7'){
i++;
System.out.print("s");
break;
}
System.out.print("r");
break;
}
System.out.print("q");
break;
}
System.out.print("p");
break;
case '8': if(sentv.charAt(next1)=='8'){
i++;
if(sentv.charAt(next2)=='8'){
i++;
System.out.print("v");
break;
}
System.out.print("u");
break;
}
System.out.print("t");
break;
case '9': if(sentv.charAt(next1)=='9'){
i++;
if(sentv.charAt(next2)=='9'){
i++;
if(sentv.charAt(next3)=='9'){
i++;
System.out.print("z");
break;
}
System.out.print("y");
break;
}
System.out.print("x");
break;
}
System.out.print("w");
break;
case '#': System.out.print(" ");
break;
default: //System.out.print();
break;
}
}
System.out.println(" \" \n");
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Old_phone {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String input, output="";
System.out.println("Please enter the string of numbers");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
input = buf.readLine();
for(int i=0; i<input.length();i++)
{
if(input.charAt(i)=='1')
i++;
else if(input.charAt(i)=='2')
{
if(input.charAt(i+1) == '1')
{
output = output + 'A';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'B';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'C';
i++;
}
}
else if(input.charAt(i)=='3')
{
if(input.charAt(i+1) == '1')
{
output = output + 'D';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'E';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'F';
i++;
}
}
else if(input.charAt(i)=='4')
{
if(input.charAt(i+1) == '1')
{
output = output + 'G';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'H';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'I';
i++;
}
}
else if(input.charAt(i)=='5')
{
if(input.charAt(i+1) == '1')
{
output = output + 'J';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'K';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'L';
i++;
}
}
else if(input.charAt(i)=='6')
{
if(input.charAt(i+1) == '1')
{
output = output + 'M';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'N';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'O';
i++;
}
}
else if(input.charAt(i)=='7')
{
if(input.charAt(i+1) == '1')
{
output = output + 'P';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'Q';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'R';
i++;
}
else if(input.charAt(i+1) == '4')
{
output = output + 'S';
i++;
}
}
else if(input.charAt(i)=='8')
{
if(input.charAt(i+1) == '1')
{
output = output + 'T';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'U';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'V';
i++;
}
}
else if(input.charAt(i)=='9')
{
if(input.charAt(i+1) == '1')
{
output = output + 'W';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'X';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'Y';
i++;
}
else if(input.charAt(i+1) == '4')
{
output = output + 'Z';
i++;
}
}
else if(input.charAt(i)=='#')
output = output + ' ';
}
System.out.println(output);
}
}
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
public class Old_phone {
public static void main(String[] args) throws IOException {
// TODO Auto-generated method stub
String input, output="";
System.out.println("Please enter the string of numbers");
BufferedReader buf = new BufferedReader(new InputStreamReader(System.in));
input = buf.readLine();
for(int i=0; i<input.length();i++)
{
if(input.charAt(i)=='1')
i++;
else if(input.charAt(i)=='2')
{
if(input.charAt(i+1) == '1')
{
output = output + 'A';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'B';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'C';
i++;
}
}
else if(input.charAt(i)=='3')
{
if(input.charAt(i+1) == '1')
{
output = output + 'D';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'E';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'F';
i++;
}
}
else if(input.charAt(i)=='4')
{
if(input.charAt(i+1) == '1')
{
output = output + 'G';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'H';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'I';
i++;
}
}
else if(input.charAt(i)=='5')
{
if(input.charAt(i+1) == '1')
{
output = output + 'J';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'K';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'L';
i++;
}
}
else if(input.charAt(i)=='6')
{
if(input.charAt(i+1) == '1')
{
output = output + 'M';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'N';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'O';
i++;
}
}
else if(input.charAt(i)=='7')
{
if(input.charAt(i+1) == '1')
{
output = output + 'P';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'Q';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'R';
i++;
}
else if(input.charAt(i+1) == '4')
{
output = output + 'S';
i++;
}
}
else if(input.charAt(i)=='8')
{
if(input.charAt(i+1) == '1')
{
output = output + 'T';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'U';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'V';
i++;
}
}
else if(input.charAt(i)=='9')
{
if(input.charAt(i+1) == '1')
{
output = output + 'W';
i++;
}
else if(input.charAt(i+1) == '2')
{
output = output + 'X';
i++;
}
else if(input.charAt(i+1) == '3')
{
output = output + 'Y';
i++;
}
else if(input.charAt(i+1) == '4')
{
output = output + 'Z';
i++;
}
}
else if(input.charAt(i)=='#')
output = output + ' ';
}
System.out.println(output);
}
}
class Program
{
static int getActualNumber(string num)
{
if (num == "#")
return 0;
if (num == "*")
return 10;
if (int.Parse(num) < 8)
return ((int.Parse(num) - 2) * 3) + 65;
return ((int.Parse(num) - 2) * 3) + 66;
}
static void Main(string[] args)
{
Console.Write("Enter number in keypad : ");
string str = Console.ReadLine();
for (int i = 0; i < str.Length; i++)
{
bool cond = true;
string numStr = str.Substring( i,1);
int numNum, count = 0;
int.TryParse(numStr, out numNum);
while (cond && i < str.Length -1)
if (str.Substring(i, 1) == str.Substring(i+1, 1))
{
count++;
++i;
}
else
cond = false;
int mod = 3;
if (numNum == 7 || numNum == 9)
mod = 4;
Console.Write((char)(getActualNumber(numStr)+count%mod));
}
Console.WriteLine();
}
}
public static String findLetters(String mixedLetters) {
int k = 0, j = 0;
StringBuilder sb = new StringBuilder();
String tokens[] = mixedLetters.split("#");
for (String words : tokens) {
char ch[] = words.toCharArray();
for (int i = 0; i < ch.length; i++) {
String temp = "";
for (j = i; j < ch.length; j++) {
if (ch[i] == ch[j])
temp += ch[i];
else
break;
}
i = j - 1;
if (wordMap.get(temp) != null)
sb.append(wordMap.get(temp));
}
sb.append(" ");
}
return sb.toString();
}
import java.util.HashMap;
import java.util.Map;
import java.util.Scanner;
public class NumberToChar {
static Map<String, String> wordMap = new HashMap<String, String>(26);
static {
wordMap.put("2", "A"); wordMap.put("22", "B"); wordMap.put("222", "C");
wordMap.put("3", "D"); wordMap.put("33", "E"); wordMap.put("333", "F");
wordMap.put("4", "G"); wordMap.put("44", "H"); wordMap.put("444", "I");
wordMap.put("5", "J"); wordMap.put("55", "K"); wordMap.put("555", "L");
wordMap.put("6", "M"); wordMap.put("66", "N"); wordMap.put("666", "O");
wordMap.put("7", "P"); wordMap.put("77", "Q"); wordMap.put("777", "R");
wordMap.put("8", "S"); wordMap.put("88", "T"); wordMap.put("888", "U"); wordMap.put("8888", "V");
wordMap.put("9", "W"); wordMap.put("99", "X"); wordMap.put("999", "Y"); wordMap.put("9999", "Z");
}
public static void main(String[] args) {
String numericValue="5288882#4448#477733288";
String words=findLetters(numericValue);
System.out.println("O/P value:: "+words);
}
public static String findLetters(String mixedLetters) {
int k = 0, j = 0;
StringBuilder sb = new StringBuilder();
String tokens[] = mixedLetters.split("#");
for (String words : tokens) {
char ch[] = words.toCharArray();
for (int i = 0; i < ch.length; i++) {
String temp = "";
for (j = i; j < ch.length; j++) {
if (ch[i] == ch[j])
temp += ch[i];
else
break;
}
i = j - 1;
if (wordMap.get(temp) != null)
sb.append(wordMap.get(temp));
}
sb.append(" ");
}
return sb.toString();
}
}
import java.util.*;
class PhonePad {
public static void main(String args[]){
String input = "22#22";
PhonePad pad = new PhonePad();
System.out.println(input + "convert to -> " + pad.parse(input));
input = "22222##2";
System.out.println(input + "convert to -> " + pad.parse(input));
}
public String parse(String input){
HashMap<Character,List<Character>> numPad = new HashMap<>();
StringBuilder output = new StringBuilder();
numPad.put('2', Arrays.asList('A','B','C'));
numPad.put('3', Arrays.asList('D','E','F'));
numPad.put('4', Arrays.asList('G','H','I'));
numPad.put('5', Arrays.asList('J','K','L'));
numPad.put('6', Arrays.asList('M','N','O'));
numPad.put('7', Arrays.asList('P','R','Q','S'));
numPad.put('8', Arrays.asList('T','U','V'));
numPad.put('9', Arrays.asList('W','X','Y','Z'));
numPad.put('#', Arrays.asList(' '));
for(int i=0; i<input.length();i++){
char ch = input.charAt(i);
int count=0;
while((i+1 < input.length()) && (ch == input.charAt(i+1)) && (count < numPad.get(ch).size()-1)){
count++;
i++;
}
output.append(numPad.get(ch).get(count));
}
return output.toString();
}
}
import java.util.*;
class PhonePad {
public static void main(String args[]){
String input = "22#22";
PhonePad pad = new PhonePad();
System.out.println(input + "convert to -> " + pad.parse(input));
input = "22222##2";
System.out.println(input + "convert to -> " + pad.parse(input));
}
public String parse(String input){
HashMap<Character,List<Character>> numPad = new HashMap<>();
StringBuilder output = new StringBuilder();
numPad.put('2', Arrays.asList('A','B','C'));
numPad.put('3', Arrays.asList('D','E','F'));
numPad.put('4', Arrays.asList('G','H','I'));
numPad.put('5', Arrays.asList('J','K','L'));
numPad.put('6', Arrays.asList('M','N','O'));
numPad.put('7', Arrays.asList('P','R','Q','S'));
numPad.put('8', Arrays.asList('T','U','V'));
numPad.put('9', Arrays.asList('W','X','Y','Z'));
numPad.put('#', Arrays.asList(' '));
for(int i=0; i<input.length();i++){
char ch = input.charAt(i);
int count=0;
while((i+1 < input.length()) && (ch == input.charAt(i+1)) && (count < numPad.get(ch).size()-1)){
count++;
i++;
}
output.append(numPad.get(ch).get(count));
}
return output.toString();
}
}
My code also covers the case where you split the input and each element of the array contains different element.
package com.rackspace.test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MobileImpl {
public String oldMobile(String input)
{
String[] inputArray = input.split("#"); // 444 55566688833 999666888
Map<Character,List<Character>> numPad = new HashMap<Character, List<Character>>();
numPad.put('2', Arrays.asList( 'A', 'B', 'C' ) );
numPad.put('3', Arrays.asList( 'D', 'E', 'F' ) );
numPad.put('4', Arrays.asList( 'G', 'H', 'I' ) );
numPad.put('5', Arrays.asList( 'J', 'K', 'L' ) );
numPad.put('6', Arrays.asList( 'M', 'N', 'O' ) );
numPad.put('7', Arrays.asList( 'P', 'Q', 'R', 'S' ) );
numPad.put('8', Arrays.asList( 'T', 'U', 'V' ) );
numPad.put('9', Arrays.asList( 'W','X', 'Y', 'Z' ) );
StringBuffer buffer = new StringBuffer();
for (String element : inputArray) {
char previous=element.charAt(0);
int count = 0;
int len = element.length()-1;
for(int i=0;i<element.length();i++)
{
char current = element.charAt(i);
if(current == previous)
{
count++;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}else
{
count = 1;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}
previous = current;
}
buffer.append(" ");
}
System.out.println(buffer.toString());
return buffer.toString();
}
}
My code also works for the case where input contains different numbers rather than repeating the same element and # and different number
567#6578#234
package com.rackspace.test;
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MobileImpl {
public String oldMobile(String input)
{
String[] inputArray = input.split("#"); // 444 55566688833 999666888
Map<Character,List<Character>> numPad = new HashMap<Character, List<Character>>();
numPad.put('2', Arrays.asList( 'A', 'B', 'C' ) );
numPad.put('3', Arrays.asList( 'D', 'E', 'F' ) );
numPad.put('4', Arrays.asList( 'G', 'H', 'I' ) );
numPad.put('5', Arrays.asList( 'J', 'K', 'L' ) );
numPad.put('6', Arrays.asList( 'M', 'N', 'O' ) );
numPad.put('7', Arrays.asList( 'P', 'Q', 'R', 'S' ) );
numPad.put('8', Arrays.asList( 'T', 'U', 'V' ) );
numPad.put('9', Arrays.asList( 'W','X', 'Y', 'Z' ) );
StringBuffer buffer = new StringBuffer();
for (String element : inputArray) {
char previous=element.charAt(0);
int count = 0;
int len = element.length()-1;
for(int i=0;i<element.length();i++)
{
char current = element.charAt(i);
if(current == previous)
{
count++;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}else
{
count = 1;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}
previous = current;
}
buffer.append(" ");
}
System.out.println(buffer.toString());
return buffer.toString();
}
}
It also covers edge cases like 678#453#234
import java.util.Arrays;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class MobileImpl {
public String oldMobile(String input)
{
String[] inputArray = input.split("#"); // 444 55566688833 999666888
Map<Character,List<Character>> numPad = new HashMap<Character, List<Character>>();
numPad.put('2', Arrays.asList( 'A', 'B', 'C' ) );
numPad.put('3', Arrays.asList( 'D', 'E', 'F' ) );
numPad.put('4', Arrays.asList( 'G', 'H', 'I' ) );
numPad.put('5', Arrays.asList( 'J', 'K', 'L' ) );
numPad.put('6', Arrays.asList( 'M', 'N', 'O' ) );
numPad.put('7', Arrays.asList( 'P', 'Q', 'R', 'S' ) );
numPad.put('8', Arrays.asList( 'T', 'U', 'V' ) );
numPad.put('9', Arrays.asList( 'W','X', 'Y', 'Z' ) );
StringBuffer buffer = new StringBuffer();
for (String element : inputArray) {
char previous=element.charAt(0);
int count = 0;
int len = element.length()-1;
for(int i=0;i<element.length();i++)
{
char current = element.charAt(i);
if(current == previous)
{
count++;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}else
{
count = 1;
if(i != len)
{
char next = element.charAt(i+1);
if(current != next)
{
System.out.println(buffer.toString());
List<Character> list = numPad.get(current);
char each = list.get(count-1);
buffer.append(each);
}
}else if(i == len)
{
buffer.append((numPad.get(current)).get(count-1));
}
}
previous = current;
}
buffer.append(" ");
}
System.out.println(buffer.toString());
return buffer.toString();
}
}
public static String inputToText(String input)
{
char [][] map = {{'A','B','C'}, {'D','E','F'}, {'G','H','I'}, {'J','K','L'}, {'M','N','O'},
{'P','Q','R','S'}, {'T','U','V'}, {'W','X','Y','Z'}};
String result = "";
for (int i=0;i<input.length();i++)
{
System.out.println("Made it in loop");
if(input.charAt(i) == '#')
result += " ";
else if (Character.getNumericValue(input.charAt(i)) >1 && Character.getNumericValue(input.charAt(i)) <= 9)
{
System.out.println("Made it to else ");
int count=0;
int pos = i;
while (pos+1 <input.length() && input.charAt(pos) == input.charAt(pos+1) )
{
count++;
pos++;
System.out.println("Finished while, with count and pos: " + count + pos);
}
result += map[Character.getNumericValue(input.charAt(i)) -2][count];
i = pos;
}
}
return result;
}
public static String inputToText(String input)
{
char [][] map = {{'A','B','C'}, {'D','E','F'}, {'G','H','I'}, {'J','K','L'}, {'M','N','O'},
{'P','Q','R','S'}, {'T','U','V'}, {'W','X','Y','Z'}};
String result = "";
for (int i=0;i<input.length();i++)
{
System.out.println("Made it in loop");
if(input.charAt(i) == '#')
result += " ";
else if (Character.getNumericValue(input.charAt(i)) >1 && Character.getNumericValue(input.charAt(i)) <= 9)
{
System.out.println("Made it to else ");
int count=0;
int pos = i;
while (pos+1 <input.length() && input.charAt(pos) == input.charAt(pos+1) )
{
count++;
pos++;
System.out.println("Finished while, with count and pos: " + count + pos);
}
result += map[Character.getNumericValue(input.charAt(i)) -2][count];
i = pos;
}
}
return result;
}
public static String inputToText(String input)
{
char [][] map = {{'A','B','C'}, {'D','E','F'}, {'G','H','I'}, {'J','K','L'}, {'M','N','O'},
{'P','Q','R','S'}, {'T','U','V'}, {'W','X','Y','Z'}};
String result = "";
for (int i=0;i<input.length();i++)
{
System.out.println("Made it in loop");
if(input.charAt(i) == '#')
result += " ";
else if (Character.getNumericValue(input.charAt(i)) >1 && Character.getNumericValue(input.charAt(i)) <= 9)
{
System.out.println("Made it to else ");
int count=0;
int pos = i;
while (pos+1 <input.length() && input.charAt(pos) == input.charAt(pos+1) )
{
count++;
pos++;
System.out.println("Finished while, with count and pos: " + count + pos);
}
result += map[Character.getNumericValue(input.charAt(i)) -2][count];
i = pos;
}
}
return result;
}
public static String inputToText(String input)
{
char [][] map = {{'A','B','C'}, {'D','E','F'}, {'G','H','I'}, {'J','K','L'}, {'M','N','O'},
{'P','Q','R','S'}, {'T','U','V'}, {'W','X','Y','Z'}};
String result = "";
for (int i=0;i<input.length();i++)
{
System.out.println("Made it in loop");
if(input.charAt(i) == '#')
result += " ";
else if (Character.getNumericValue(input.charAt(i)) >1 && Character.getNumericValue(input.charAt(i)) <= 9)
{
System.out.println("Made it to else ");
int count=0;
int pos = i;
while (pos+1 <input.length() && input.charAt(pos) == input.charAt(pos+1) )
{
count++;
pos++;
System.out.println("Finished while, with count and pos: " + count + pos);
}
result += map[Character.getNumericValue(input.charAt(i)) -2][count];
i = pos;
}
}
return result;
}
Here is my version
public class KeyPad {
public static void main(String[] args){
HashMap<Character, List<Character>> numPad = BuildHashMap();
Scanner in = new Scanner(System.in);
String input = in.nextLine();
String[] tokens = input.split("#");
for(String tok: tokens){
if(tok.length() > 1){ //user has either pressed different keypands or pressed same keypad more than once
int count = 0;
Character cCurrent, cNext;
for(int i=0; i<tok.length()-1; i++){
cCurrent = tok.charAt(i);
cNext = tok.charAt(i+1);
if(cCurrent == cNext){ //same key pressed twice or more
count ++;
if(count == numPad.get(cCurrent).size()-1 ){
//this case if a particular key has been pressed more than 3/4 times. This print is for rolling over
System.out.println(numPad.get(cCurrent).get(count+1));
count = 0;
}
}
else{ //there are difference between current and next key
//either we have seen same number before or not. 'count' variable will tell the story
if(count == 0){//keys are different, print the Character
System.out.print(numPad.get(cCurrent).get(0));
}
else{
System.out.print(numPad.get(cCurrent).get(count));
count = 0;
}
}
}
//Deal with the last character of "tok" separately since the for loop ends before processing it
if(count == 0){
System.out.print(numPad.get(tok.charAt(tok.length()-1)).get(0));
}
else{
System.out.print(numPad.get(tok.charAt(tok.length()-1)).get(count));
}
}
else{ //if the length of the tok is only 1. one number followed by #
System.out.print(numPad.get(tok.charAt(0)).get(0));
}
System.out.print(" "); //print the blank space for hash
}
}
private static HashMap<Character, List<Character>> BuildHashMap() {
HashMap<Character, List<Character>> numPad = new HashMap<Character, List<Character>>();
numPad.put('1', new ArrayList<>());
numPad.put('2', Arrays.asList('A', 'B', 'C'));
numPad.put('3', Arrays.asList( 'D', 'E', 'F' ) );
numPad.put('4', Arrays.asList( 'G', 'H', 'I' ) );
numPad.put('5', Arrays.asList( 'J', 'K', 'L' ) );
numPad.put('6', Arrays.asList( 'M', 'N', 'O' ) );
numPad.put('7', Arrays.asList( 'P', 'Q', 'R', 'S' ) );
numPad.put('8', Arrays.asList( 'T', 'U', 'V' ) );
numPad.put('9', Arrays.asList( 'W','X', 'Y', 'Z' ) );
numPad.put('0', new ArrayList<Character>() );
return numPad;
}
}
#include<iostream>
#include<string>
#include<unordered_map>;
using namespace std;
string convertkeypad(string s)
{
int i;
char n;
string out = "";
unordered_map<char, string> pad;
pad['2'] = "ABC";
pad['3'] = "DEF";
pad['4'] = "GHI";
pad['5'] = "JKL";
pad['6'] = "MNO";
pad['7'] = "PQRS";
pad['8'] = "TUV";
pad['9'] = "WXYZ";
pad['#'] = " ";
for (i = 0; i < s.length();++i)
{
n = s[i];
int k = 0;
if (s[i+1] == n)
{
++k;
++i;
if (s[i+1] == n)
{
++k;
++i;
if (s[i+1] == n)
{
++k;
++i;
}
}
}
out = out + (pad[n])[k];
}
return out;
}
int main()
{
string s =convertkeypad("567#76534#453");
return 0;
}
This is my program
Dictionary<int, ArrayList> numPad = new Dictionary<int, ArrayList>();
numPad.Add(2, new ArrayList(new char[] { 'A', 'B', 'C' }));
numPad.Add(3, new ArrayList(new char[] { 'D', 'E', 'F' }));
numPad.Add(4, new ArrayList(new char[] { 'G', 'H', 'I' }));
numPad.Add(5, new ArrayList(new char[] { 'J', 'K', 'L' }));
numPad.Add(6, new ArrayList(new char[] { 'M', 'N', 'O' }));
numPad.Add(7, new ArrayList(new char[] { 'P', 'Q', 'R', 'S' }));
numPad.Add(8, new ArrayList(new char[] { 'T', 'U', 'V' }));
numPad.Add(9, new ArrayList(new char[] { 'X', 'Y', 'Z' }));
numPad.Add(0, new ArrayList(new char[] { ' ' }));
string input = "33#62#819332";
var inputs = input.ToCharArray();
bool flag = true;
ArrayList chars = new ArrayList();
for (int i = 0; i < inputs.Length; i++)
{
if (inputs[i] == '#')
{
numPad.TryGetValue(0, out chars);
Console.Write(chars[0]);
}
else
{
int dicKey;
int.TryParse(inputs[i].ToString(), out dicKey);
if (flag)
{
numPad.TryGetValue(dicKey, out chars);
flag = false;
}
else
{
Console.Write(chars[dicKey - 1]);
chars = new ArrayList();
flag = true;
}
}
}
Console.ReadKey();
Dictionary<int, ArrayList> numPad = new Dictionary<int, ArrayList>();
numPad.Add(2, new ArrayList(new char[] { 'A', 'B', 'C' }));
numPad.Add(3, new ArrayList(new char[] { 'D', 'E', 'F' }));
numPad.Add(4, new ArrayList(new char[] { 'G', 'H', 'I' }));
numPad.Add(5, new ArrayList(new char[] { 'J', 'K', 'L' }));
numPad.Add(6, new ArrayList(new char[] { 'M', 'N', 'O' }));
numPad.Add(7, new ArrayList(new char[] { 'P', 'Q', 'R', 'S' }));
numPad.Add(8, new ArrayList(new char[] { 'T', 'U', 'V' }));
numPad.Add(9, new ArrayList(new char[] { 'X', 'Y', 'Z' }));
numPad.Add(0, new ArrayList(new char[] { ' ' }));
string input = "33#62#819332";
var inputs = input.ToCharArray();
bool flag = true;
ArrayList chars = new ArrayList();
for (int i = 0; i < inputs.Length; i++)
{
if (inputs[i] == '#')
{
numPad.TryGetValue(0, out chars);
Console.Write(chars[0]);
}
else
{
int dicKey;
int.TryParse(inputs[i].ToString(), out dicKey);
if (flag)
{
numPad.TryGetValue(dicKey, out chars);
flag = false;
}
else
{
Console.Write(chars[dicKey - 1]);
chars = new ArrayList();
flag = true;
}
}
}
Console.ReadKey();
public class numberToletter {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String text="4#44#222";
String[] array=text.split("#");
String[] keys={"0","1","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ}"};
for(int i=0;i<array.length;i++){
int index=array[i].charAt(0)-'0';
int len=array[i].length()-1;
System.out.print(keys[index].charAt(len)+" ");
}
}
}
public class numberToletter {
/**
* @param args
*/
public static void main(String[] args) {
// TODO Auto-generated method stub
String text="4#44#222";
String[] array=text.split("#");
String[] keys={"0","1","ABC","DEF","GHI","JKL","MNO","PQRS","TUV","WXYZ}"};
for(int i=0;i<array.length;i++){
int index=array[i].charAt(0)-'0';
int len=array[i].length()-1;
System.out.print(keys[index].charAt(len)+" ");
}
}
}
public class OldMobilePhone {
public static void main(String[] args) {
Mobile mobile = new Mobile();
System.out.println(mobile.convertNumberToString("#666#22"));
System.out.println(mobile.convertNumberToString("789#66#63234"));
System.out.println(mobile.convertNumberToString("4#44#222"));
}
}
public class Mobile {
private HashMap<Character, String> map;
public Mobile() {
map = new HashMap<>();
map.put('1', "");
map.put('2', "ABC");
map.put('3', "DEF");
map.put('4', "GHI");
map.put('5', "JKL");
map.put('6', "MNO");
map.put('7', "PQRS");
map.put('8', "TUV");
map.put('9', "WXYZ");
map.put('0', "");
}
// since we need 2 numbers to determine a value
// if prev = 2 and next = 2, then we B
private Character getCharacterFromNumber(char prev, char next) {
if (prev == '1' || prev == '0') return null;
int nextNum = next - '0' - 1;
if (nextNum >= map.get(prev).length() || nextNum < 1) return null;
else {
return this.map.get(prev).charAt(nextNum);
}
}
public String convertNumberToString(String num) {
StringBuilder sb = new StringBuilder();
char[] chars = num.toCharArray();
int index = 1;
while (index < chars.length) {
Character prevLetter = chars[index - 1];
Character currentLetter = chars[index];
if (prevLetter == '#') {
index++;
sb.append(" ");
} else if (getCharacterFromNumber(prevLetter, currentLetter) == null) {
index++;
} else {
sb.append(getCharacterFromNumber(prevLetter, currentLetter));
index += 2;
}
}
return sb.toString();
}
}
This should do it, not sure if there is a better way to get the mapping of num pad into code (that is, using some algo or base n division). But this is a first pass at it.
- just.a.coder May 03, 2015