Programming Contest: T9
Tuesday, October 17th, 2006Description
Take in a dictionary of words, and implement the T9 program, which aids text message typing into cell phones. Sample input and output available at tnine.in and tnine.out.
[ complete description ] [ tnine.java ]
Solution
String[] dict;
String[] ndict;
public void go() throws Exception
{
Scanner in = new Scanner(new File("tnine.in"));
int n = in.nextInt();
in.nextLine();
dict = new String[n];
ndict = new String[n];
for(int i=0; i<n; i++)
{
String word = in.nextLine();
dict[i] = word;
ndict[i] = getintword(word);
}
int m = in.nextInt();
in.nextLine();
for(int i=0; i<m; i++)
{
String sent = in.nextLine();
String tran = getSentence(sent.split(" "));
System.out.println("Message #"+(i+1)+": "+tran+"n");
}
}
public String getintword(String word)
{
String ret= "";
for(int i=0; i<word.length(); i++)
{
switch(word.charAt(i))
{
case 'a': case 'b': case 'c': ret+="2"; break;
case 'd': case 'e': case 'f': ret+="3"; break;
case 'g': case 'h': case 'i': ret+="4"; break;
case 'j': case 'k': case 'l': ret+="5"; break;
case 'm': case 'n': case 'o': ret+="6"; break;
case 'p': case 'q': case 'r': case 's': ret+="7"; break;
case 't': case 'u': case 'v': ret+="8"; break;
case 'w': case 'x': case 'y': case 'z': ret+="9"; break;
}
}
return ret;
}
public String getSentence(String[] words)
{
boolean mult = false;
int total = 1;
String ret = "", nwrd = "";
for(int i=0; i<words.length; i++)
{
if(getNumWords(words[i])==0)
{
return "not a valid text";
}
else if(mult || getNumWords(words[i])>1)
{
total *= getNumWords(words[i]);
mult = true;
}
else
{
nwrd = getWord(words[i]);
ret += nwrd + " ";
}
}
if(mult)
return "there are "+total+" possible messages";
else
return ret.trim();
}
public String getWord(String word)
{
for(int i=0; i<dict.length; i++)
{
if(word.equals(ndict[i]))
{
return dict[i];
}
}
return "!!!";
}
public int getNumWords(String word)
{
int count=0;
for(int i=0; i<dict.length; i++)
{
if(word.equals(ndict[i]))
{
count++;
}
}
return count;
}