Dismiss Notice
Join Physics Forums Today!
The friendliest, high quality science and math community on the planet! Everyone who loves science is here!

Java Code for Insult Generator

  1. Mar 3, 2009 #1
    Hi, I have to do a homework assignment for my intro to computer porgramming class and i have to write a program that creates insult sentences. My professor gave us some code to start with and we had to fill in the functions(professor gave us the names of these functions and the name of the program loop). I need help getting the function to work. I included the code i was given and below that i put the functions and what i did so far.


    This is the code I was given:


    Code (Text):
     
    import java.util.Random ;


    public class Generator {

      public static void main(String[] args) {
        for (int n = 0 ; n < 10 ; n++) {
          System.out.println( generateSentence("S") ) ;
        }
      }

      ... PUT YOUR OTHER FUNCTIONS HERE ...


      /// The method selectExpansion(Category) will randomly expand
      /// Category according to the following grammar.  Returns "error" if
      /// there is no expansion.

      static Random RANDOM = new Random() ;

      static String[] GRAMMAR = {
        "S -> NAME VP",
        "VP -> V NP",
        "NP -> ART NN",
        "NN -> ADJ NN",
        "NN -> N",
        "ART -> a",
        "V -> is",
        "V -> looks like",
        "V -> acts like",
        "NAME -> dr aronis",
        "NAME -> mr aronis",
        "NAME -> john aronis",
        "ADJ -> stupid",
        "ADJ -> geeky",
        "ADJ -> ugly",
        "N -> idiot",
        "N -> teacher",
        "N -> fool"
      } ;

      public static String selectExpansion(String category) {
        // Variables:
        String thisRule = "", ruleLHS = "", ruleRHS = "" ;
        int numberOfExpansions = 0, expansionToUse = 0 ;
        // Count expansions for category:
        for (int n = 0 ; n < GRAMMAR.length ; n++) {
          thisRule = GRAMMAR[n] ;
          ruleLHS = thisRule.substring(0,thisRule.indexOf(" -> ")) ;
          if ( ruleLHS.equals(category) ) numberOfExpansions++ ;
        }
        // Return error if no expansions:
        if ( numberOfExpansions == 0 ) return "error" ;
        // Randomly select which expansion to use:
        expansionToUse = Math.abs(RANDOM.nextInt() % numberOfExpansions) ;
        // Go through rules while counting down through expansions of category,
        // and break with selected expansion:
        for (int n = 0 ; n < GRAMMAR.length ; n++) {
          thisRule = GRAMMAR[n] ;
          ruleLHS = thisRule.substring(0,thisRule.indexOf(" -> ")) ;
          ruleRHS = thisRule.substring(thisRule.indexOf(" -> ") + 4) ;
          if ( ruleLHS.equals(category) && (expansionToUse == 0) ) break ;
          if ( ruleLHS.equals(category) ) expansionToUse-- ;
        }
        return ruleRHS ;
      }

    }

    // End-of-File

     


    I have to fill in the functions(function names were given) and this is what I did so far(i know i probably did some stuff wrong plus i need to add some more code...but im just not sure what):

    Code (Text):

     public static void generateSentence(String insult){
        string insult;
        string left;
        string right;
        while(hasCategory(insult)){
          Category = firstCategory(insult);
          left = beforeFirstCategory(insult);
          right = afterFirstCategory(insult);
          insult = left + selectExpansion(Category) + right;
        }
      }
     
      public static boolean hasCategory(String s){
        for(int i=0; i<=s.length(); i++){
          if(charAt(i)>='A' && charAt(i)<='Z'){
            return true;
          }
        }  
        return false;
      }
     
      public static int beginningOfCategory(String s){
        for(int i=0; i<s.length(); i++){
          if(charAt(i)>='A' && charAt(i)<='Z'){
            return i;      
          }
        }
      }
     
      public static int endOfCategory(String s){
        for(int i=0; i<s.length(); i++){
          if(!(charAt(i)>'A' && charAt(i)<='A')){
            return i;  
          }
        }
      }
         
      public static String beforeFirstCategory (String s){
        beginningOfCategory(String s);
        return s.substring(0,beginningOfCategory(String s));
      }  
                 
      public static String firstCategory(String s){
        beginningOfCategory(String s);
        endOfcategory(String s);
        return s.substring(beginningOfCategory(String s),endOfCategory(String s));
      }
     
      public static String afterFirstCategory(String s){
       endCategory(String s);
       s.length();
       return s.substring(endOfCategory(String s),s.length());
      }
     
     
  2. jcsd
  3. Mar 4, 2009 #2
    You're almost there.

    Code (Text):
     
    public static int endOfCategory(String s){
        for(int i=0; i<s.length(); i++){
          if(!(charAt(i)>'A' && charAt(i)<='A')){      // <---- N.B.
            return i;  
          }
        }
      }
     
    This line doesn't work: (e > 'A' && e <= 'A') is never true, for any expression e, it's a contradiction.

    What is the test you want, for endOfCategory? When you find a nonterminal (a 'category'), represented as a string of all-capital letters, at what point does it end?

    "abc DEF ghi"

    Take a short example string (like this one), and work out where the nonterminal is, where it starts and ends. Then take what you're doing, and generalize it. If your algorithm works on any string, it will also work on this particular, simple string: it's a test.
     
  4. Mar 4, 2009 #3
    (rayboyz, this part won't help you at all, you can safely ignore it)

    To those PF'ers who think Scheme/Lisp is a bad language for teaching programming, that you should teach language used in industry right away (otherwise you're wasting time), take a look at the instructor's code here. This is a very good example. The problem here is a very simple, almost beautiful idea - generating sentences to follow a grammar. Though it is a simple problem, it has been overwhelmed, drowned in irrelevant implementation details - an absolute mess of string manipulation. Instead of solving the problem itself, poor 'royboyz' is spending all his work stuff like <= comparisons of ASCII characters with 'A'/'Z', to test case. This stuff couldn't be farther away from the real problem, whose main solution ('selectExpansion') is so messy that it's just given as a black box, because the instructor didn't trust their students to solve it (within the constraints of C-like code). 'Royboyz' completely misses out on the meat of the problem - he or she is unfairly deprived.

    Instead, the SICP type approach with Scheme works at a much higher level of language than machine details: it deals directly with symbolic manipulation. This makes this exact problem here, far simpler, shorter, and directly accessible to new students. Take a look at the lisp solution: it was written by Peter Norvig (currently Director of Research at Google), in his book "Paradigms of Artificial Intelligence Programming". (There are two versions, one simple and one improved). And apparently you read the whole chapter online (edit: no, just parts of it), in the Google Books preview (it is chapter 2, "a simple lisp program"):

    http://norvig.com/paip/simple.lisp

    http://norvig.com/paip.html

    http://books.google.com/books?id=QzGuHnDhvZIC&pg=PA34&source=gbs_search_s&cad=0

    http://img171.imageshack.us/img171/420/41y2fdaae4l.jpg [Broken]


    If this isn't eye-opening enough by itself, bear in mind this solution predates the Java language which the OP is written in.
     
    Last edited by a moderator: May 4, 2017
Know someone interested in this topic? Share this thread via Reddit, Google+, Twitter, or Facebook




Similar Discussions: Java Code for Insult Generator
Loading...