CS1020 Week 5: 12th Feb 2015 Contents Sit-in lab #1 Common Mistakes Take-home Lab #2 2 Week 5 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 doubt Study 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 4 Week 5 Understand Question This was a sit in lab OOOO X O X X O X O X OO How many possible segment sizes? How many possible advertisement widths? This This This This This was was was was was a a a a a sit sit sit sit sit in in in in in lab lab lab lab lab Segments have same size S 5 OOOO OOOO OOOO OOOO OOOO X X X X X O O O O O X X X X X X X X X X O O O O O X X X X X O O O O O X X X X X OO OO OO OO OO Adverts have same width W Week 5 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 6 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 5 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 7 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 5 Design Algorithm <WordS > <WordS > <W> Check charAt(S) Check charAt(S + S+1) Check charAt(S + 2(S+1)) < ! >X<!>X!X<!>X<!>X<!> Check charAt(W) Check charAt(W + W+1) Check charAt(W + 2(W+1)) As long as < message.length() As long as < layout.length() 8 Week 5 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 9 Week 5 Design Program while there hasNextLine() // containing 1 message or layout Message input = read nextLine() - _message : String : Message result = solve(input) + isPossibleSize( “This was a ”… println result pintSize : int) : int isPossibleSize(1) ?? false 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 10 Week 5 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 case returns true if message can be broken down into segments of given size (adverts can have given width), false otherwise 11 Week 5 Write Skeleton Pre-condition: What must be true before method executes? Parameter values e.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 system e.g. Connection open, other program waiting for message 12 Week 5 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. 13 Week 5 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; } 14 Week 5 Test javac FileName.java compile source file into bytecode java DriverClassName manual test run java DriverClassName < input.in test run java DriverClassName < input.in > output.actual save output to a file diff output.actual output.out compare your output with the expected output 15 Week 5 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 16 Week 5 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 17 Week 5 Common Mistakes (Lab TAs: Please customise this section on the common mistakes your class made in Sit-in Lab #1, or reminders for your class.) 18 Week 5 Take-home Lab #2 Exercise 1 – KWIC Index System Week 5 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: 20 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. Week 3 KWIC Index Key Word In Context index system Scanner sc sc.next() vs. sc.nextLine() Scan numOfWordToIgnore && numOfTitle Add them to respective ArrayList<String> 21 KWIC Index Class: KWICIndexSystem Week 5 KWIC Index Class: KWIC ArrayList<String> Modularity 22 Every single method in the KWIC class is IMPORTANT! Week 5 KWIC Index API Use ArrayList<E> class (requirement) Check out the API! http://docs.oracle.com/javase/7/docs/api/java/util/ArrayList.h tml Use Collections class and its sort method Check out the API! http://docs.oracle.com/javase/7/docs/api/java/util/Collections .html 23 Week 5 Take-home Lab #2 Exercise 2 – Simple Social Network Week 5 Objective is to implement a simple social network with some operations: Register a new user Set a user follows another user Set a user unfollow another user Find mutual follow users (R userName) (F userA userB) (U userA userB) (M) Solution: 25 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. Week 3 Social Network Simple Social Network Things to take note: 26 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. Week 3 Social Network Understand Question Social Network Class: User Create Object: User Data attributes : String name, User[ ] following, … Constructor: public User(String Name) Methods: public void setFollow(User user) public void setUnfollow(User user) Create your own helper methods: 27 Initialize your data attributes 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 5 Social Network Class: SocialNetwork SocialNetwork class: how to use User class! Data attributes: User[ ] allUsers, int numOfUsers Constructor: public SocialNetwork() Register a new user: public void registerUser(String name) Use setFollow method in User class. Set user A unfollow user B: public void setUnfollow(User A, User B) Create an object of User class with given name. Set user A follows user B: public void setFollow(User A, User B) Initialize your data attributes Use setUnfollow method in User class. Find mutual follow users 28 Can use isFollowing method in User class. Week 5 Fixed length vs. Dynamic length Access by index vs. Access by iterator Complexity (time and space) … 29 Social Network Array vs. ArrayList<E> Week 5 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 31 Gold Hunters Gold Hunters 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 Week 5 Gold Hunters Store input map in 2D array Integer Array (Store both input and output) Character Array (Store input) + Integer Array (Store 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?) 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. 32 Week 5 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). 33 +1 +1 +1 (R-1,C-1) (R-1,C) (R-1,C+1) +1 * +1 (R,C-1) (R,C) (R,C+1) +1 +1 +1 (R+1,C-1) (R+1,C-1) (R+1,C+1) Gold Hunters Compute amount of gold on the map (1/2) location of mine Week 5 Use double for-loop to go through array and locate each mine on the map If mine located at index (R,C) Gold Hunters Compute amount of gold on the map (2/2) Use double for-loop to go through indices of the possible cells within the 3x3 area of effect for (int i=R-1; i <= R+1; i++) for (int j=C-1; j <= C+1; j++) ... 34 If an index is valid (not outside boundary of array), increment amount of gold in that cell by 1 Week 5 Double for-loop to go through the integer array and print out the gold in each cell Print ‘*’ if cell is a mine cell. 35 Gold Hunters Output gold on map Week 5 END OF FILE