- #1

- 2

- 0

import java.util.Random ;

public class Generator {

////////////////////////////////////////////////////////////////////

//

// Generate 10 sentences.

//

public static void main(String[] args) {

for (int n = 0 ; n < 10 ; n++) {

System.out.println( generate("S") ) ;

}

}

////////////////////////////////////////////////////////////////////

//

// Completely expand category (usually S).

//

public static String generate(String category) {

... YOUR DEFINITION OF GENERATE() HERE ...

}

... YOUR OTHER FUNCTIONS HERE ...

////////////////////////////////////////////////////////////////////

//

// Select_Expansion(Category) will randomly expand Category

// according to the following grammar. Returns "error" if there is

// no expansion.

//

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

"ADJ -> nice",

"ADJ -> mean",

"ADJ -> smart",

"ADJ -> stupid",

"ADJ -> hip",

"ADJ -> geeky",

"ADJ -> normal",

"ADJ -> strange",

"ADJ -> great",

"ADJ -> terrible",

"N -> person",

"N -> teacher",

"N -> fool"

} ;

static Random generator = new Random() ;

public static String Select_Expansion(String Category) {

// Variables:

String This_Rule = "", Rule_LHS = "", Rule_RHS = "" ;

int Number_of_Expansions = 0, Expansion_to_Use = 0 ;

// Count expansions for Category:

for (int n = 0 ; n < Grammar.length ; n++) {

This_Rule = Grammar[n] ;

Rule_LHS = This_Rule.substring(0,This_Rule.indexOf( " -> ")) ;

if ( Rule_LHS.equals(Category) ) Number_of_Expansions++ ;

}

// Return error if no expansions:

if ( Number_of_Expansions == 0 ) return "error" ;

// Randomly select which expansion to use:

Expansion_to_Use = Math.abs(generator.nextInt() % Number_of_Expansions) ;

// Go through rules while counting down through expansions of Category,

// and break with selected expansion:

for (int n = 0 ; n < Grammar.length ; n++) {

This_Rule = Grammar[n] ;

Rule_LHS = This_Rule.substring(0,This_Rule.indexOf( " -> ")) ;

Rule_RHS = This_Rule.substring(This_Rule.indexOf(" -> ") + 4) ;

if ( Rule_LHS.equals(Category) && (Expansion_to_Use == 0) ) break ;

if ( Rule_LHS.equals(Category) ) Expansion_to_Use-- ;

}

return Rule_RHS ;

}

////////////////////////////////////////////////////////////////////

}

// End-of-File