首页
网站开发
桌面应用
管理软件
微信开发
App开发
嵌入式软件
工具软件
数据采集与分析
其他
首页
>
> 详细
CSE 143编程讲解、辅导Python,CS,Java程序 解析Java程序|讲解SPSS
项目预算:
开发周期:
发布时间:
要求地区:
CSE 143: Computer Programming II Winter 2021
Take-home Assessment 5: Grammar Solver due February 11, 2021 11:59pm
This assignment will assess your mastery of the following objectives:
• Implement a well-designed Java class to meet a given specification.
• Implement recursive methods to solve a naturally-recursive problem.
• Implement a public-private recursive pair.
• Choose an appropriate data structure to represent specified data.
• Follow prescribed conventions for code quality, documentation, and readability.
Overview: Languages, Grammars, and BNF
In this assessment, you will write a class GrammarSolver that will be able to generate random sentences
(or other output) from a set of specially-formatted rules. These rules are called a grammar and are used
to define a language. Our grammars will be written in Backus-Naur Form (BNF).
Formal Languages
A formal language is a set of words and symbols along with a set of rules defining how those symbols may
be used together. These rules dictate what are considered valid constructions in the defined language.
For example, in English, “A boy threw the ball.” is a valid sentence, but “A threw boy ball the” is not,
despite consisting of the same words, because the words are put together in an invalid way.
Grammars
A grammar is a way of describing the syntax and symbols of a formal language. Grammars have two types
of “symbols” (e.g., words, phrases, sentences): terminals and non-terminals. A terminal is a fundamental
word or symbol in the language. For example, in English, any single word would be considered a terminal.
A non-terminal is a symbol that is used to define specific groups of symbols that may be used in the
language. In a grammar for English, we might have non-terminals such as “adjective,” “noun phrase,”
and “sentence” to name a few.
sentence
verb
runs
object
dog
article
the
For example, consider the following simple language:
• Terminals: the, a, cat, dog, runs, walks
• Non-terminals:
– sentence: “article and object and verb”
– article: “the or a”.
– object: “cat or dog”.
– verb: “runs or walks”.
This language allows the following sentences:
“the cat runs” “the cat walks” “a cat runs” “a cat walks”
“the dog runs” “the dog walks” “a dog runs” “a dog walks”
Page 1 of 10
Backus-Naur Form (BNF)
Backus-Naur Form (BNF) is a specific format for specifying grammars. Each line of BNF looks like the
following:
nonterminal::=rule|rule|...|rule
Each “rule” is some sequence of terminals or non-terminals separated by whitespace. The ‘|’ character
separates different possible rules for the same non-terminal. For example, the grammar specified above
written in BNF would look like:
sentence::=article object verb
article::=the|a
object::=cat|dog
verb::=runs|walks
Notice that the non-terminal sentence has a single option consisting of multiple non-terminals, whereas
the others non-terminals each consist of multiple options.
Rules may be duplicated for the same non-terminal to make a particular expansion more likely than others.
For example, suppose the above grammar were modified as follows:
sentence::=article object verb
article::=the|a
object::=cat|cat|dog
verb::=runs|walks
This grammar would produce the same sentences as the original grammar, but sentences containing “cat”
would be twice as likely to occur as sentences containing “dog.”
In addition, for this assessment, you may assume the following about all BNF rules:
• Each line will contain exactly one occurrence of ::= which will be the separator between the name
of a non-terminal and its options.
• A pipe (|) will separate each option for a non-terminal. If there is only one option for a particular
non-terminal (like with sentence above), there will be no pipe on that line.
• Whitespace separates tokens but doesn’t haven any special meaning. There will be at least one
whitespace character between each part of a single rule. Extra whitespace should be ignored.
• Symbols are case-sensistive. (For example,
would not be considered the same symbol as
.)
• A terminal is any symbol that does not appear on the left-hand side of a rule.
• The text before the “::=” is not empty, does not contain a pipe (|) character, and does not contain
any whitespace.
• The text after the “::=” will be nonempty.
Program Behavior
In this assessment you will write a class that accepts a list of rules for a grammar in Backus-Naur Form
and allows the client to randomly generate elements of the grammar. You will use recursion to implement
the core of your algorithm.
Page 2 of 10
We have provided you with a client program, GrammarMain.java, that handles the file processing and
user interaction. This program reads a BNF grammar input text file and passes its entire contents to you
as a List of Strings. You will write a class GrammarSolver that generates random results based on
the rules provided.
GrammarSolver
Your GrammarSolver class should have the following constructor:
public GrammarSolver(List
rules)
This constructor should initialize a new grammar over the given BNF grammar rules where each rule
corresponds to one line of text. You should use regular expressions (see below) to break apart the
rules and store them into a Map so that you can look up parts of the grammar efficiently later.
You should not modify the list passed in. You should throw an IllegalArgumentException if the
list is empty or if there are two or more entries in the grammar for the same non-terminal.
Your GrammarSolver should also implement the following public methods:
public boolean grammarContains(String symbol)
This method should return true if the given symbol is a non-terminal in the grammar and false
otherwise.
For example, for the grammar above, grammarContains("sentence") would return true and
grammarContains("foo") or grammarContains("boy") (“boy” is a terminal in the language)
would return false.
public String getSymbols()
This method should return a string representation of the various nonterminal symbols from the
grammar as a sorted, comma-separated list enclosed in square brackets
For example, calling getSymbols() for the previous grammar would give: “[article, object,
sentence, verb]”.
public String[] generate(String symbol, int times)
This method should generate times random occurrences of the given symbol and return them as
a String[]. Each string generated should be compact in the sense that there should be
exactly one space between each terminal and there should be no leading or trailing spaces.
If times is negative, you should throw an IllegalArgumentException. If the String argument
passed is not a non-terminal in your grammar you should throw an IllegalArgumentException.
When generating a non-terminal symbol in your grammar, each of the rules on the right-hand side
of the grammar should be applied with equal probability.
⑧
Each written
rule should
equally likely,
but a rule may
occur more often
if it appears
as an option
more than once.
Page 3 of 10
Sample Grammar and Executions
Complex BNF (sentence.txt)
::=
::=
|
::=Hadi|Jazmin|Ali|Spot|Fred|Elmo
::=
|
::=big|green|wonderful|faulty|subliminal|pretentious
::=the|a
::=dog|cat|man|university|father|mother|child|television
::=
|
::=taught|honored|waved to|helped
::=died|collapsed|laughed|wept
Example Random Sentence Diagram
child
wonderful
green
the
honored
Fred
Partial Example Execution (user input underlined)
Welcome to the cse143 random sentence generator.
What is the name of the grammar file? sentence.txt
Available symbols are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
How many do you want me to generate? 5
Hadi found Jazmin
Spot helped the big cat
Elmo died
the green mother wept
the subliminal green man laughed
Available symbols are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
More example program executions are found at the end of the spec.
Page 4 of 10
Implementation Guidelines
GrammarSolver Constructor
For this assessment, you MUST represent your grammar using a Map, where the keys of the map are
the non-terminals of the grammar, and the values are the options for expansion the corresponding nonterminal.
You should choose an appropriate data structure for the values in your Map to effectively
represent the grammar rules and make the operations required by the class convenient and efficient.
generate Algorithm
The generate method will generate a random occurrence of a given non-terminal NT. You MUST use
the following recursive algorithm in your implementation of this method:
Choose a random expansion rule R for the non-terminal NT. For each of the symbols in the
rule R, generate a random occurrence of that symbol. If the symbol is a terminal, the expansion
is simply the symbol itself. If the symbol is a non-terminal, you should generate an expansion
using a recursive call.
Remember that it is acceptable to have a loop inside your recursion. (In fact, you will likely want one as
part of this algorithm!) The directory crawler program from class will serve as a good guide for how to
write this program. In that example, we iterated over the different files in a directory and used recursion
to list the files in each subdirectory. For your GrammarSolver, you will iterate over the different symbols
in the chosen role and use recursion to generate an expansion for each symbol. You may also find that
you will want to use a public/private pair for this recursive task.
Testing Your Solution
We are providing another tool that is linked on the section for this assignment to check the output of
your generate method to make sure it is producing valid output.
⑧
Remember to
remove any
debugging
code when you
submit.
You can test that the correct whitespace is produced from generate by using some non-whitespace
character (e.g. ~) instead of spaces and inspecting the output visually.
Splitting Strings
In this assignment, it will be useful to know how to split strings apart in Java. In particular, you will need
to split the various options for rules on the | character, and then, you will need to split the pieces of a
rule apart by spaces.
To do this, you should use the split method of the String class, which takes a String delimiter
(e.g. “what to split by”) as a parameter and returns your original large String as an array of smaller
Strings.
The delimiter String passed to split is called a regular expression, which are strings that use a particular
syntax to indicate patterns of text. A regular expression is a String that “matches” certain sequences.
For instance, “abc” is a regular expression that matches “a followed by b followed by c”.
You do not need to have a deep understanding of regular expressions to complete this assessment. Here
are some specific regular expressions that will help you with particular splitting steps for your class:
• Splitting Non-Terminals from Rules. Given a String, line, to split line based on where
::= occurs, you could use the regular expression “::=” (since you are looking for these literal
characters). For example:
String line = "example::=foo bar |baz";
String[] pieces = line.split("::="); // ["example", "foo bar |baz"]
Page 5 of 10
• Splitting Different Rules. Given a String, rules, to split rules based on where the | character
is, it looks similar to the above, except, in regular expressions, | is a special character. So, we must
escape it (just like \n or \t). So, the regular expression is “\\|”. (Note that we need two slashes
because slashes themselves must be escaped in Strings.) For example:
String rules = "foo bar|baz |quux mumble";
String[] pieces = rules.split("\\|"); // ["foo bar", "baz ", "quux mumble"]
• Splitting Apart a Single Rule. Given a String, rule, to split rule based on whitespace, we
must look for “at least one whitespace”. We can use \\s to indicate “a single whitespace of any
kind: \t, space, etc. And by adding + afterwards, the regular expression is interpreted as “one or
more of whitespace”. For example:
String rule = "the quick brown fox";
String[] pieces = rule.split("\\s+"); // ["the", "quick", "brown", "fox"]
Removing Whitespace from the Beginning and the End of a String
One minor issue that comes up with splitting on whitespace as above is that if the String you are splitting
begins with a whitespace character, you will get an empty String at the front of the resulting array.
Given a String, str, we can create a new String that omits all leading and trailing whitespace removed:
String str = " lots of spaces \t";
String trimmedString = str.trim(); // "lots of spaces"
Development Strategy and Hints
The generate method is the most difficult, so we strongly suggest you write it last. Remember that it
is helpful to tackle difficult methods using “iterative development” where you solve simple versions of the
problem first.
Random programs can be difficult to validate correctness, and the generate method you will implement
uses randomness to decide which rule for a given non-terminal to use. To help you debug and validate
your output, we have provided a grammar verifier tool on the course website that verifies your output
follows the grammar rules (but ignores whitespace).
If your recursive method has a bug, try putting a debug println that prints your parameter values to
see the calls being made.
Code Quality Guidelines
In addition to producing the behavior described above, your code should be well-written and meet all
expectations described in the grading guidelines, Code Quality Guide, and Commenting Guide. For this
assessment, pay particular attention to the following elements:
SortedMap
Because we want you to guarantee the keys of your map are sorted, we will ask you to use the
SortedMap
interface for this assignment instead of the Map
interface. The SortedMap
interface is essentially the same as the Map interface, except it requires the keys be sorted. This means
TreeMap is a valid SortedMap implementation, but HashMap is not. You can use all the same methods
on a SortedMap as you could on a Map.
Page 6 of 10
Generic Structures
You should always use generic structures. If you make a mistake in specifying type parameters, the
Java compiler may warn you that you have “unchecked or unsafe operations” in your program. If you
use jGRASP, you may want to change your settings to see which line the warning refers to. Go to
Settings/Compiler Settings/Workspace/Flags/Args and then uncheck the box next to “Compile”
and type in: -Xlint:unchecked
Data Fields
Properly encapsulate your objects by making data your fields private. Avoid unnecessary fields; use
fields to store important data of your objects but not to store temporary values only used in one place.
Fields should always be initialized inside a constructor or method, never at declaration.
Exceptions
The specified exceptions must be thrown correctly in the specified cases. Exceptions should be thrown
as soon as possible, and no unnecessary work should be done when an exception is thrown. Exceptions
should be documented in comments, including the type of exception thrown and under what conditions.
Commenting
Each method should have a header comment including all necessary information as described in the
Commenting Guide. Comments should be written in your own words (i.e. not copied and pasted from
this spec) and should not include implemenation details.
Running and Submitting
If you believe your behavior is correct, you can submit your work by clicking the "Mark" button in the Ed
assessment. You will see the results of some automated tests along with tentative grades. These grades
are not final until you have received feedback from your TA.
You may submit your work as often as you like until the deadline; we will always grade your most recent
submission. Note the due date and time carefully—work submitted after the due time will not be
accepted.
Getting Help
If you find you are struggling with this assessment, make use of all the course resources that are available
to you, such as:
• Reviewing relevant examples from class
• Reading the textbook
• Visiting office hours
• Posting a question on the message board
Collaboration Policy
Remember that, while you are encouraged to use all resources at your disposal, including your classmates,
all work you submit must be entirely your own. In particular, you should NEVER look at a solution
to this assessment from another source (a classmate, a former student, an online repository, etc.). Please
review the full policy in the syllabus for more details and ask the course staff if you are unclear on whether
or not a resource is OK to use.
Page 7 of 10
Reflection
In addition to your code, you must submit answers to short reflection questions. These questions will
help you think about what you learned, what you struggled with, and how you can improve next time.
The questions are given in the file GrammarSolverReflection.txt in the Ed assessment; type your
responses directly into that file.
Page 8 of 10
Sample Execution #1 (user input underlined)
Welcome to the cse143 random sentence generator.
What is the name of the grammar file? sentence.txt
Available symbols to generate are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
How many do you want me to generate? 5
a
the
the
a
the
Available symbols to generate are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
How many do you want me to generate? 5
Elmo
a green big pretentious green pretentious subliminal university
the pretentious cat
Jazmin
the pretentious subliminal mother
Available symbols to generate are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
How many do you want me to generate? 20
a faulty dog laughed
Ali helped a wonderful dog
Spot collapsed
the green father wept
Spot laughed
Elmo taught Ali
the subliminal green man honored Fred
a wonderful faulty big father laughed
the faulty faulty university taught the faulty dog
Elmo helped the green university
Hadi helped the pretentious man
the pretentious man died
Ali laughed
the pretentious subliminal child found Hadi
Elmo wept
a wonderful wonderful faulty child collapsed
Spot found the subliminal subliminal pretentious university
the green father helped the wonderful cat
a faulty television wept
the faulty mother laughed
Available symbols to generate are:
[
,
,
,
,
,
,
,
,
,
]
What do you want generated (return to quit)?
Page 9 of 10
Sample Execution #2 (user input underlined)
Welcome to the cse143 random sentence generator.
What is the name of the grammar file? sentence2.txt
Available symbols to generate are:
[E, F1, F2, OP, T]
What do you want generated (return to quit)? T
How many do you want me to generate? 5
42
- y
x
x
( ( 1 ) )
Available symbols to generate are:
[E, F1, F2, OP, T]
What do you want generated (return to quit)? E
How many do you want me to generate? 10
x - 1
0
sin ( 1 + 92 + - 1 / 42 )
max ( y , 92 )
42 % 1
- 42
92
1
92
42 - sin ( 1 )
Available symbols to generate are:
[E, F1, F2, OP, T]
What do you want generated (return to quit)?
Page 10 of 10
软件开发、广告设计客服
QQ:99515681
邮箱:99515681@qq.com
工作时间:8:00-23:00
微信:codinghelp
热点项目
更多
urba6006代写、java/c++编程语...
2024-12-26
代做program、代写python编程语...
2024-12-26
代写dts207tc、sql编程语言代做
2024-12-25
cs209a代做、java程序设计代写
2024-12-25
cs305程序代做、代写python程序...
2024-12-25
代写csc1001、代做python设计程...
2024-12-24
代写practice test preparatio...
2024-12-24
代写bre2031 – environmental...
2024-12-24
代写ece5550: applied kalman ...
2024-12-24
代做conmgnt 7049 – measurem...
2024-12-24
代写ece3700j introduction to...
2024-12-24
代做adad9311 designing the e...
2024-12-24
代做comp5618 - applied cyber...
2024-12-24
热点标签
mktg2509
csci 2600
38170
lng302
csse3010
phas3226
77938
arch1162
engn4536/engn6536
acx5903
comp151101
phl245
cse12
comp9312
stat3016/6016
phas0038
comp2140
6qqmb312
xjco3011
rest0005
ematm0051
5qqmn219
lubs5062m
eee8155
cege0100
eap033
artd1109
mat246
etc3430
ecmm462
mis102
inft6800
ddes9903
comp6521
comp9517
comp3331/9331
comp4337
comp6008
comp9414
bu.231.790.81
man00150m
csb352h
math1041
eengm4100
isys1002
08
6057cem
mktg3504
mthm036
mtrx1701
mth3241
eeee3086
cmp-7038b
cmp-7000a
ints4010
econ2151
infs5710
fins5516
fin3309
fins5510
gsoe9340
math2007
math2036
soee5010
mark3088
infs3605
elec9714
comp2271
ma214
comp2211
infs3604
600426
sit254
acct3091
bbt405
msin0116
com107/com113
mark5826
sit120
comp9021
eco2101
eeen40700
cs253
ece3114
ecmm447
chns3000
math377
itd102
comp9444
comp(2041|9044)
econ0060
econ7230
mgt001371
ecs-323
cs6250
mgdi60012
mdia2012
comm221001
comm5000
ma1008
engl642
econ241
com333
math367
mis201
nbs-7041x
meek16104
econ2003
comm1190
mbas902
comp-1027
dpst1091
comp7315
eppd1033
m06
ee3025
msci231
bb113/bbs1063
fc709
comp3425
comp9417
econ42915
cb9101
math1102e
chme0017
fc307
mkt60104
5522usst
litr1-uc6201.200
ee1102
cosc2803
math39512
omp9727
int2067/int5051
bsb151
mgt253
fc021
babs2202
mis2002s
phya21
18-213
cege0012
mdia1002
math38032
mech5125
07
cisc102
mgx3110
cs240
11175
fin3020s
eco3420
ictten622
comp9727
cpt111
de114102d
mgm320h5s
bafi1019
math21112
efim20036
mn-3503
fins5568
110.807
bcpm000028
info6030
bma0092
bcpm0054
math20212
ce335
cs365
cenv6141
ftec5580
math2010
ec3450
comm1170
ecmt1010
csci-ua.0480-003
econ12-200
ib3960
ectb60h3f
cs247—assignment
tk3163
ics3u
ib3j80
comp20008
comp9334
eppd1063
acct2343
cct109
isys1055/3412
math350-real
math2014
eec180
stat141b
econ2101
msinm014/msing014/msing014b
fit2004
comp643
bu1002
cm2030
联系我们
- QQ: 9951568
© 2021
www.rj363.com
软件定制开发网!