Answer to Monday's Grinch Question
Sunday December 28, 2008
The programming question this week was to decode a hidden message within the text of a Christmas quote from Dr Suess' How The Grinch Stole Christmas.
The cipher code:
5-7-1-3 8-7-1-3 7-3 3-3 5-9-1-2 4-5-0-3 1-4 2-2-1-2 2-4-0-6 4-6 4-2-1-2 1-13 4-4-0-7when applied to the quotation becomes:
is it Christmas without a box with a ribbon or a puzzling packageHere's my version of the program:
import java.util.Scanner;
public class BookCipher {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.println("Enter in the code text: ");
String bookText = input.nextLine();
//it makes life easier to remove the spaces
//between sentences
bookText = bookText.replace(". ", ".");
bookText = bookText.replace("? ", "?");
//split the code text into sentences using
//a regex expression. It says split on any
//quesion mark or fullstop
String[] sentences = bookText.split("[\\?\\.]");
System.out.println("Enter in text cipher:");
String cipher = input.nextLine();
String[] ciphers = cipher.split(" ");
StringBuilder hiddenSentence = new StringBuilder();
for (String s:ciphers)
{
String[] positions = s.split("-");
//find right sentence
String sentence = sentences[Integer.parseInt(positions[0])-1];
//get rid of any commas from sentence
sentence = sentence.replace(",", "");
String[] words = sentence.split(" ");
//find the right word
String word = words[Integer.parseInt(positions[1])-1];
//if there is a substring defined in the cipher
//then find the word within a word
if (positions.length == 4)
{
String subWord = word.substring(Integer.parseInt(positions[2]), Integer.parseInt(positions[3]));
hiddenSentence.append(subWord + " ");
}
else
{
hiddenSentence.append(word + " ");
}
}
System.out.println(hiddenSentence);
}
}


No comments yet. Leave a Comment