1 / 33

CS1020

CS1020. Week 5 : 13 th February 2014. Contents. Part 1 : Discussion on Sit-in Lab # 1 Part 2: Common Mistakes Part 3 : Discussion on Take-home Lab #2 Part 4: Selected Practice Exercise. Part 1. Discussion on Sit-in Lab #1. Set A: Longest Substring. Longest Substring. Task:

javen
Télécharger la présentation

CS1020

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. CS1020 Week 5: 13thFebruary 2014

  2. Contents • Part 1: Discussion on Sit-in Lab #1 • Part 2: Common Mistakes • Part 3: Discussion on Take-home Lab #2 • Part 4: Selected Practice Exercise Week 5

  3. Part 1 Discussion on Sit-in Lab #1 Week 5

  4. Set A: Longest Substring Longest Substring • Task: • To find the length of the longest substring in the giving string. • The longest substring should contain no repeated characters. • Example: • Input: ahhejjkaeK1i97ae • Output: 7 (longest substrings are “aeK1i97”, “eK1i97a”, and “K1i97ae”.) • In the discussion that follows, we assume no array is used.

  5. Set A: Algorithm (1/4) Longest Substring • Where is the starting point of the longest substring without repeated characters? ahhejjkaeK1i97ae ahhejjkaeK1i97ae h ah • Try all possible starting position (each character in the string) • Requires a loop through each character in string ahhejjkaeK1i97ae hej

  6. Set A: Algorithm (2/4) Longest Substring • How to find the longest substring from each starting position? Extend substring by 1 character Starting position ahhejjkaeK1i97ae ahhejjkaeK1i97ae • Requires an inner loop that keeps adding a character to the current substring ahhejjkaeK1i97ae Keep extending substring by 1 character until no further extension possible

  7. Set A: Algorithm (3/4) Longest Substring • How to tell if the current character can be used to extend the substring? Currently at this character ahhejjkaeK1i97ae Compare ‘j’ with characters in current substring “he” • Before extending substring need to compare character with all the characters in the substring to check it has not appeared before • Required another nested loop! OR • use indexOf(intch, intfromIndex)  how?

  8. Set A: Algorithm (4/4) Longest Substring • Both lower and upper case letters are used • Need to convert given string to upper or lower case before going into algorithm • toLowerCase()/toUpperCase() • Possible improvement to algorithm • Don’t have to try all character positions in the given string Do I have to try longest substring starting at ‘e’ and longest substring starting from ‘j’ ? ahhejjkaeK1i97ae Longest substring without repeated characters starting from ‘h’ at position 2

  9. Set A: Program (1/2) Longest Substring import java.util.*; /* Getting length of the longest substring without repeated characters in a string */ public class LongestSubstring { public static void main(String[] args) { Scanner sc = new Scanner (System.in); String inStr = new String(sc.next().toLowerCase()); int maxSubstrLength = -1; // startPos is the starting index of the current // substring without repeated characters in the string int startPos = 0;

  10. while (true) { int endPos = startPos+1; int newStartPos = 0,curLength = 0; // keep extending curr substring until hit a repeated char while (endPos < inStr.length()) { boolean stop = false; // check if curr char is repeated before further extending for (int counter=endPos-1; counter>=startPos; counter--) if (inStr.charAt(counter) == inStr.charAt(endPos)) { stop = true; newStartPos = counter+1; // new start pos for next // longest substring candidate break; } if (stop)break; endPos++; } curLength = endPos-startPos; startPos = newStartPos; // update the longest length if curr substring is longest if (curLength > maxSubstrLength) maxSubstrLength = curLength; if (endPos >= inStr.length()) // no more candidates to test break; } System.out.println(maxSubstrLength); } } Set A: Program (2/2) Longest Substring

  11. Set B: Anagrams (1/2) Anagrams • Task: • To test if two given strings are anagrams of each other (composed of same characters but in different arrangements) • Example: • Input: Quid est veritasEst vir qui adset • Output: true • In the discussion that follows, we assume no array is used.

  12. Set B: Anagrams (2/2) Anagrams • Both strings are anagrams of each other iff • Both contains the same set of unique characters • Each unique character appears the same number of times • They are not the same (there is some difference in the arrangement of the characters) Quid estveritas Est virqui adest Aappears 1 time D appears 1 time E appears 2 times I appears 2 times Q appears 1 time R appears 1 time S appears 2 times T appears 2 times U appears 1 time V appears 1 time

  13. Set B: Algorithm (1/4) Anagrams • Process the 2 strings • Case does not matter change both strings to upper or lower case using toLowerCase() or toUpperCase() • White space is not considered remove white spaces using replaceAll(" ","") • Check that the 2 strings are not the same • Use equals() method or the compareTo(String anotherString)method. • Check that the 2 strings are of the same length required, why? • Use length() method to compare

  14. Set B: Algorithm (2/4) Anagrams • Pick one of the string and go through each character in the string  requires a loop • For each character in step 4, go through both strings to count its appearance frequency  Requires two inner loops, one for each string Current character Quid estveritas Est vir qui adest Go through both strings to get frequency of ‘e’, which is both 2 Quid estveritas Est vir qui adest

  15. Set B: Algorithm (3/4) Anagrams • Return false anytime the 2 frequency counts are not the same • Return true if frequency counts are the same after going through all the characters in the picked string

  16. Set B: Algorithm (4/4) Anagrams • Possible impovement to algorithm • Don’t have to count frequency of all characters in the picked string 1st time encounter ‘e’, we will calculate its frequency Quid estveritas Est vir qui adest 2nd time encounter ‘e’, we don’t have to calculate its frequency again • After counting frequency of encountered character, replace all its occurance in the picked string with some non-English character e.g ‘#’ how? • So when encounter a ‘#’ simply skip it

  17. Set B: Program (1/2) Anagrams import java.util.*; /* Check if two strings are anagrams of each other */ public class Anagram { public static void main(String[] args) { Scanner sc = new Scanner (System.in); // read in lower case version of each string String inStr1 = new String(sc.nextLine().toLowerCase()); String inStr2 = new String(sc.nextLine().toLowerCase()); Boolean isAnagram = true; // remove white spaces inStr1 = inStr1.replaceAll(" ",""); inStr2 = inStr2.replaceAll(" ","");

  18. // if not identical and length are the same if ((inStr1.compareTo(inStr2) != 0) && (inStr1.length() == inStr2.length())) { // get each unique character in the first string for (int charIndex=0; charIndex<inStr1.length(); charIndex++) { int numCharInStr1 = 0,numCharInStr2 = 0; char curChar = inStr1.charAt(charIndex); // check that all non-'#' chars have equal occurence in both strings if (curChar != '#') { for (int counter=0; counter < inStr1.length(); counter++) if (inStr1.charAt(counter) == curChar) numCharInStr1++; for (int counter=0; counter < inStr2.length(); counter++) if (inStr2.charAt(counter) == curChar) numCharInStr2++; if (numCharInStr1 != numCharInStr2) { isAnagram = false; break; } // replace all occurance of curChar with '#' inStr1 = inStr1.replace(curChar,'#'); } } } else isAnagram = false; System.out.println(isAnagram.toString()); } } Set B: Program (2/2) Anagrams

  19. Part 2 Common mistakes Week 5

  20. 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.)

  21. Part 3 Discussion on Take-Home Lab #2 Week 5

  22. Gold Hunters Gold Hunters • 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

  23. Store input map in 2D array Gold Hunters • 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.

  24. Compute amount of gold on the map (1/2) Gold Hunters • 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). location of mine

  25. Compute amount of gold on the map (2/2) Gold Hunters • 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 for (inti=R-1; i <= R+1; i++) for (int j=C-1; j <= C+1; j++) ...

  26. Output gold on map Gold Hunters • Double for-loop to go through the integer array and print out the gold in each cell • Print ‘*’ if cell is a mine cell.

  27. Part 4 Selected Practice Exercise Week 5

  28. Ex 24: Matrix Transform (1/5) • Given a matrix of size N x N and some operations of rotation or reflection, determine the final state of the matrix. • The operations are: • Rotate clockwise by X degrees, X = 90, 180, or 270 • Reflect across the x-axis. • Reflect across the y-axis. Week 5

  29. Ex 24: Matrix Transform (2/5) • Rotate clockwise by 90 c c c r r r • Use a for loop to process all elements one by one • Let (r, c) be the coordinates of an element. • #1 is at (0,0); after 90clockwise rotation, it will be at (0,2). Week 5

  30. Ex 24: Matrix Transform (3/5) • Rotate clockwise by 90 c c c r r r • #2 is at (0,1); after 90 rotation, it will be at (1,2). • #3 is at (0,2); after90 rotation, it will be at (2,2). • Do you see any pattern? • Rotation 180  2 ×rotation 90 • Rotation 270  3 ×rotation 90 • Hence, we need onlydefine 90 rotation Week 5

  31. Ex 24: Matrix Transform (4/5) • There is also a pattern for reflection • Reflect across x-axis c c r r • Do you see any pattern? Week 5

  32. Ex 24: Matrix Transform (5/5) • Reflect across y-axis c c r r • Do you see any pattern? Week 5

  33. END OF FILE

More Related