1. Home
  2. Computing & Technology
  3. Java
photo of Paul Leahy
Paul's Java Blog

By Paul Leahy, About.com Guide to Java

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-7

when applied to the quotation becomes:

is it Christmas without a box with a ribbon or a puzzling package

Here'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);
  }
}
Comments

No comments yet. Leave a Comment

Leave a Comment

Line and paragraph breaks are automatic. Some HTML allowed: <a href="" title="">, <b>, <i>, <strike>

Discuss
Community Forum
Explore Java
About.com Special Features

Stay connected and entertained with reviews on tips on the latest HDTVs, cellphones and more. More >

Easy ways to connect two computers for networking purposes. More >

  1. Home
  2. Computing & Technology
  3. Java

©2009 About.com, a part of The New York Times Company.

All rights reserved.