Upload
alijah-swindle
View
219
Download
3
Embed Size (px)
Citation preview
CS1020Week 5: 12th Feb 2015
Contents
Sit-in lab #1Common MistakesTake-home Lab #2
Week 52
Sit-in Lab #1
Set A – Message Set B – Wall
Week 5
Advice Understand question thoroughly
What does the output represent? How does each piece of information help you?
Ask your invigilator when in doubtStudy the given input and output files
Design algorithm thoroughly before coding
Don’t use unfamiliar data structures e.g. [], ArrayList, Arraylist?, java.lang.reflect.Array? Sit-in labs are set to be done using topics covered; there is
no need to use advanced topics not yet covered in class
Code incrementally and keep testing
Week 54
Understand Question
This was a sit in lab
How many possible segment sizes?
This was a sit in labThis was a sit in labThis was a sit in labThis was a sit in labThis was a sit in lab
Segments have same size S
OOOO X O X X O X O X OO
How many possible advertisement widths?
OOOO X O X X O X O X OOOOOO X O X X O X O X OOOOOO X O X X O X O X OOOOOO X O X X O X O X OOOOOO X O X X O X O X OO
Adverts have same width W
Week 55
Generalize Problem
This was a sit in lab<WordS > <WordS > <W>Exactly 1 space betw.
words
<W > was…Segment not ≥1 word(s)
<W > was…“Was” split across segments
OOOO X O X X O X O X OO
< ! >X<!>X!X<!>X<!>X<!>
No adjacent doors, doors at ends
< ! >X<!>X …Cannot end at door
< ! >X<!>X …Cannot end at that location
Week 56
Design Algorithm
< W> <W> W <W> <>…Check message.charAt(S-1)
Check message.charAt(S)
Check message.charAt(S+1)
Only need to check for ‘ ’
If middle char is ‘ ’ left and right are letters
If middle char is not ‘ ’
invalid segment size
OOOO X O X X …Check layout.charAt(W-1) == ‘ ’
Check layout.charAt(W) == ‘X’
Check layout.charAt(W+1) == ‘ ’
Only need to check for ‘X’
If middle char is ‘X’ advert ends at immed. left advert starts at immed. Right
If middle char is not ‘X’
advert ends at invalid point
Week 57
Design Algorithm
<WordS > <WordS > <W>
Check charAt(S)
Check charAt(S + S+1)
Check charAt(S + 2(S+1))
As long as < message.length()
< ! >X<!>X!X<!>X<!>X<!>
Check charAt(W)
Check charAt(W + W+1)
Check charAt(W + 2(W+1))
As long as < layout.length()
Week 58
Design Program
while there hasNextLine() // containing 1 message or layout
input = read nextLine()
result = solve(input)
println result
static solve(input : String) : int
create new Message/Layout(input) // instantiate object
possibilities = 0
for (int size/width = 1; size <= input.length(); size++)if object.isPossible…(size/width) then possibilities++
return possibilities
Week 59
Design Program
while there hasNextLine() // containing 1 message or layout
input = read nextLine()
result = solve(input)
println result
static solve(input : String) : int
create new Message/Layout(input) // instantiate object
possibilities = 0
for (int size/width = 1; size <= input.length(); size++)if object.isPossible…(size) then possibilities++
return possibilities
: Message
Message
- _message : String
+ isPossibleSize(pintSize : int) : int
“This was a ”…
isPossibleSize(1) ?? false
Week 510
Write Skeleton
static solve(input : String) : int
pre-cond:input not NULL or empty, must be valid msg/layout
isPossible…(size/width : int) : boolean // instance method
pre-cond:1 <= given size/width <= message/layout length()
post-cond: // same as description in this casereturns true if message can be broken down into segments of
given size (adverts can have given width), false otherwise
Week 511
Write Skeleton
Pre-condition: What must be true before method executes?
Parameter valuese.g. 1 <= width <= layout length
Values of some other attributes in this object/class(method that removes student) e.g. Student data already filled
State of some other part of the systeme.g. Connection open, other program waiting for message
Week 512
Write Skeleton
Post-condition: What must be true after method executes?
(Scanner’s nextLine() method) e.g. Return value
returns the next token preceding the first “\n” character What happens to some other attribute/object
One “\n” character from the stream is discarded
State of some other part of the system(close() method) e.g. The Scanner and the underlying stream is closed. Subsequent calls to next…() methods will result in IllegalStateException being thrown.
Week 513
Algo Code
Check charAt(S)
Check charAt(S + S+1)
Check charAt(S + 2(S+1))
/*…*/
public boolean isPossible…(int size/width) {
for (int doorIdx = width; doorIdx < _layout.length();
doorIdx += width +1)if (this._layout.charAt(width) != ‘ ’) return false;
return true;
}
Week 514
Test
javac FileName.javacompile source file into bytecode
java DriverClassNamemanual test run
java DriverClassName < input.intest run
java DriverClassName < input.in > output.actualsave output to a file
diff output.actual output.outcompare your output with the expected output
Week 515
Refactor
Cleanup indentation Ensure comments are meaningful and generally accurate Cleanup obviously redundant logic
(Pretend you are another coder) Cleanup comments Check pre-/post-conditions Check method names and variable names
Follow Java naming convention Meaningful/descriptive
Week 516
Challenge Yourself
After Sit-in-Lab ask yourself how you could have coded better ask yourself how you could have improved your
algorithm revise what you are unsure of try the other problem set under test conditions
Since we have learnt arrays and are learning Collections: Use int[] primitive 1-D array to improve solve()’s efficiency Use ArrayList<Integer> to improve solve()’s efficiency
Week 517
(Lab TAs: Please customise this section on the common mistakes your class made in Sit-in Lab #1, or reminders for your class.)
Common Mistakes
Week 518
Take-home Lab #2
Exercise 1 – KWIC Index System
Week 5
Week 320
Key Word In Context index system Objective is to implement KWIC index system
with some operations: Circular shift a string Capitalize the first character of keyword Order all the title in alphabetical order
Solution: Implement the given two classes: KWIC.class and
KWICIndexSystem.class Using ArrayList. You should know how to
add/delete/search an element in an ArrayList.
KWIC Index
Class: KWICIndexSystem
Scanner sc
sc.next() vs. sc.nextLine()
Scan numOfWordToIgnore && numOfTitle
Add them to respective ArrayList<String>
Week 521
KWIC Index
Class: KWIC
ArrayList<String>
Modularity Every single method in the KWIC class is IMPORTANT!
Week 522
KWIC Index
API
Use ArrayList<E> class (requirement) Check out the API!
http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.html
Use Collections class and its sort method Check out the API!
http://docs.oracle.com/javase/7/docs/api/java/util/Collections.html
Week 523
KWIC Index
Take-home Lab #2
Exercise 2 – Simple Social Network
Week 5
Week 325
Simple Social Network Objective is to implement a simple social
network with some operations: Register a new user (R userName) Set a user follows another user (F userA userB) Set a user unfollow another user (U userA userB) Find mutual follow users (M)
Solution: Implement the given two classes: SocialNetwork.class
and User.class Using Array. You should know how to add/delete/search
an element in an array.
Social N
etwork
Week 326
Understand Question Things to take note:
Assume user name is unique; no users with same name will be registered.
R user1 user1 will not be provided in the input Multiple users can be registered in one line operation:
R user1 user2 user3 user4 .... A user cannot follows himself/herself. You must deal with
the case when F userA userA provided in the input.
Social N
etwork
Class: User
Create Object: User Data attributes : String name, User[ ] following, … Constructor: public User(String Name)
Initialize your data attributes Methods:
public void setFollow(User user) public void setUnfollow(User user)
Create your own helper methods: eg. public boolean isFollowing(User user) //check is this user
following an given user; eg. public String getName() //get the name of this user ….
Week 527
Social N
etwork
Class: SocialNetwork
SocialNetwork class: how to use User class! Data attributes: User[ ] allUsers, int numOfUsers Constructor: public SocialNetwork()
Initialize your data attributes Register a new user: public void registerUser(String name)
Create an object of User class with given name. Set user A follows user B: public void setFollow(User A, User B)
Use setFollow method in User class. Set user A unfollow user B: public void setUnfollow(User A, User B)
Use setUnfollow method in User class. Find mutual follow users
Can use isFollowing method in User class.
Week 528
Social N
etwork
Array vs. ArrayList<E>
Fixed length vs. Dynamic length
Access by index vs. Access by iterator
Complexity (time and space)
…
Week 529
Social N
etwork
Take-home Lab #2
Exercise 3 – Gold Hunters
Week 5
Objective is to output how much gold there is in each cell on the map given the position of mines.
Solution Store input map in a 2D array Compute amount of gold on the map Output map showing amount of gold in each non-mine
cell
Gold HuntersG
old Hunters
Week 531
Integer Array (Store both input and output) Only manipulate 1 array Different states of a cell need to be represented by carefully
chosen values, e.g. cannot use values 0 to 8 to represent mine cells (why?)
Character Array (Store input) + Integer Array (Store output) Store the input as is. Encode different states of a cell in the character array. Integer
array only stores the gold amount in each cell. Need to deal with 2 arrays.
Either way is fine.
Store input map in 2D arrayG
old Hunters
Week 532
Each mine “adds” 1 gold to every neighboring cell around it.
Maximum area of effect is 3x3 square around the mine (excluding its own cell).
Compute amount of gold on the map (1/2)
+1(R-1,C-1)
+1(R-1,C)
+1(R-1,C+1)
+1(R,C-1)
*(R,C)
+1(R,C+1)
+1(R+1,C-1)
+1(R+1,C-1)
+1(R+1,C+1)
location of mine
Gold H
unters
Week 533
Use double for-loop to go through array and locate each mine on the map
If mine located at index (R,C) Use double for-loop to go through indices of the possible
cells within the 3x3 area of effect
If an index is valid (not outside boundary of array), increment amount of gold in that cell by 1
Compute amount of gold on the map (2/2)
for (int i=R-1; i <= R+1; i++) for (int j=C-1; j <= C+1; j++) ...
Gold H
unters
Week 534
Double for-loop to go through the integer array and print out the gold in each cell
Print ‘*’ if cell is a mine cell.
Output gold on mapG
old Hunters
Week 535
END OF FILE