Presentation is loading. Please wait.

Presentation is loading. Please wait.

CS1020 – Data Structures And Algorithms 1 AY Semester 2

Similar presentations


Presentation on theme: "CS1020 – Data Structures And Algorithms 1 AY Semester 2"— Presentation transcript:

1 CS1020 – Data Structures And Algorithms 1 AY2015-16 Semester 2
Take-Home Lab #01 CS1020 – Data Structures And Algorithms 1 AY Semester 2

2 Problem 1 Measurement

3 Measurement You are given a number N. N rows follow.
Each row contains: Name of a student Height of a student (in cm) Weight of a student (in kg) Measurement

4 How? Data Storing Data Processing Measurement

5 Array Solution VS Non-Array Solution Measurement

6 Array solution Measurement
Store the height, weight, and name of each student in an array of the appropriate data type. Linear scan the height[] array, keeping the index of the maximum and minimum height. Retrieve the height, weight and name of the tallest student and the shortest student using the index you got from the previous step. Calculate the BMI and print the result. Measurement

7 When is it necessary to update the variables above?
Non-Array solution We do not actually need to store all the data in an array. Initialise variables that keep track of the minimum height so far, maximum height so far, as well as the name and height of both the (current) tallest and (current) shortest student. Read the input using a scanner, update the variables when necessary. Calculate the BMI and print the result. When is it necessary to update the variables above? Measurement

8 Code Snippet Initialise Variables Measurement
Scanner sc = new Scanner(System.in); int heightOfCurrentShortestStudent = Integer.MAX_VALUE; int heightOfCurrentTallestStudent = Integer.MIN_VALUE; int weightOfCurrentShortestStudent = 0; int weightOfCurrentTallestStudent = 0; String nameOfCurrentShortestStudent = ""; String nameOfCurrentTallestStudent = ""; Initialise Variables Measurement

9 Code Snippet Process Input Measurement
for (int i = 0; i < n; i++) { //for every line of the input } String currentName = ??? (use your Scanner here) //how to get the name of the current student? int currentHeight = ??? //how to get the height of the current student? int currentWeight = ??? //how to get the weight of the current student? if (currentHeight < heightOfCurrentShortestStudent) { //what do you need to do here? } if (currentHeight > heightOfCurrentTallestStudent) { sc.nextLine(); //what is the purpose of this? Process Input Measurement

10 ? How do I print to two decimal places? Measurement
Hint: System.out.printf(…); Measurement

11 Problem 2 Island

12 An example of a valid Hyrule map with two islands
You are given a map of Hyrule consisting of many islands. The map is a matrix of size R x C filled with ‘0’s and ‘1’s. Your job: count the number of islands based on the given map (you need N tickets to go to N islands). 1 An example of a valid Hyrule map with two islands Island

13 VS Standard (Tedious-To-Code) Solution (Very) Simple Solution Island
Hints: All islands are rectangular. Every plot of land is a part of an island (Very) Simple Solution Island

14 ? Any Ideas? Island

15 Standard Solution Island
Step 1: Find the top-left corner of each island. for (int i = 0; i < row; i++) { for (int j = 0; j < col; j++) { if(map[i][j] == 1) { //Step 2 //Step 3 //use a counter } Island

16 Similar for height Standard Solution Island
Step 2: Find the width (and height) of that island. int position = i; while (map[position][j]==1) position++; //then how do you know the width of this island? Similar for height Island

17 Update the ‘1’s on the current island to be ‘0’s
Standard Solution Step 3: How to avoid repeated count? Update the ‘1’s on the current island to be ‘0’s 1 1 1 Island

18 ? Easy “Lazy” Solution 1 Look for this pattern:
Step 1: Find the top-left corner of each island, with a twist. 1 Look for this pattern: Increment counter each time you see that pattern ? What if the “1” is on the left or top of the map? 1 Island

19 Trick Island

20 Technique Technique: Just add a row and column of ‘0’s to the map Such extra data are called sentinels. 1 Island

21 Technique Technique: Just add a row and column of ‘0’s to the map Such extra data are called sentinels. 1 count = 3 Island

22 (after adding a row and column of ‘0’s)
Our Sample Input (after adding a row and column of ‘0’s) Another Example (after adding a row and column of ‘0’s) 1 1 count = 2 count = 3 Island

23 Code Snippet for (int i = 1; i <= row; i++) {//why start from 1? for (int j = 1; j <= col; j++) { if (isTopLeftCornerOfAnIsland(map, i, j)) { count++; } boolean isTopLeftCornerOfAnIsland(int[][] map, int i, int j) { return map[i][j] == 1 && map[i-1][j] == 0 && map[i][j-1] == 0; } Island

24 Problem 3 Find X

25 Question Find X Map is divided into RxC squares, (R rows, C columns)
‘Super X’ Square of size at least 3 Composed entirely by X on both diagonals. Find the number of ‘Super X’ in the grid Find X 25

26 Super X 7 6 X X 7 6 7 x 7 Super X 6 x 6 Super X Find X

27 Is this a Super X? Find X Square? At least size 3?
9 X Square? At least size 3? All Xs on left diagonal? All Xs on right diagonal? 7 Find X

28 Breakdown Read Input Calculate number of Super-X Print Output Find X

29 Read Input 1st line contains two numbers R (no. of rows) and C (no. of columns) Use nextInt() Next R line contains C characters each. Each line represents one row in the treasure map. Read each row using nextLine() or next(); For loop that iterates C time Find X

30 Store Map Find X Option 1: Option 2: String[] map = new String[R];
Each element of the array in the entire row Use String.charAt(c) to read each element in the row later Option 2: char[][] map = new char[R][C] Read entire row first (String row = sc.nextLine();) Use row.toCharArray() Break the row up into its separate elements as a char[] String[][] map will work too Use row.split(“”); Find X

31 An array of character arrays?
char[][] map = new char[R][C] new char[8][7]; 7 X map[0] map[1] map[3][0] map[2] map[3] 8 map[4] map[5] map[6] map[7] map[7][4] Find X

32 Input Find X public static void main(String[] args) {
//read input using Scanner Scanner = new Scanner(System.in); int R = sc.nextInt(); //number of rows int C = sc.nextInt(); //number of columns char[][] map = new char[R][C]; //initialise sc.nextLine(); //to move onto the next line //for each row for (int i = 0; i < numOfRows; i++) { String rowString = sc.nextLine(); map[i] = rowString.toCharArray(); } Find X

33 Output Find X From question:
The number of ‘super X’ in the map Just use the println() method to print the output Do not print other strings with the number E.g. “Number of Super X is: 4” public static void main(String[] args) { //read input using Scanner ….. int count = getNumOfSuperX(map); System.out.println(count); } Find X

34 Breaking it down Find the number of squares with ‘Super X’ of size larger than 3 in the grid For all the squares of the different sizes in the grid Check whether it is a Super X For each size For each square in the grid of that size Check whether it is a super X Find X

35 Incremental Programming
Breaking the problem down into sub-problems Solve each of them separately Create a method that when given a square, will tell us if it is a super X Call that method for each of the square of each size later Find X

36 Find X From the centre Expand in all 4 directions Possible, but tricky

37 Checking if a square is a super X
Square of size at least 3 Composed entirely by X on both diagonals. Check if both diagonals of a square are all Xs 7 6 X X 7 6 Find X

38 Checking if a square is a super X
isSuperX method Parameters Top left corner rowIndex of top left hand corner columnIndex of top left hand corner size of square (number of elements in each row/col) X Find X

39 Checking if a square is a super X
Iterate through both diagonals (from top left and from top right) Check if they are all Xs 2 methods isRightToLeftAllX isLeftToRightAllX Find X

40 Checking if a square is a super X
//Assume rowNum and colNum are within grid, rowNum + size – //1 and colNum + size – 1 are within grid boolean isSuperX(int rowNum, int colNum, int size) { //can put an if condition here that will return //false if the square is outside of the grid int leftCornerCol = colNum; int rightCornerCol = colNum + size – 1; int row = rowNum; return isLeftToRightAllX(leftCornerCol, row, size) && isRightToLeftAllX(rightCornerCol, row, size) Find X

41 Iterating through the diagonal
boolean isLeftToRightAllX(int x, int y, int size) { //for size times for (int i = 0; i < size; i++) { char currentElement = map[x][y]; if (currentElement != ‘X’) { return false; //stop evaluating } else { x += 1; //advance y += 1; } return true; Find X

42 Hooray! Find X Now we have our isSuperX method!
Given the row and column of the top left hand corner We can check if it is a super X! :D Just call this method for All squares of each size Across different sizes Find X

43 Iterate through all squares
Assume fixed size of 3 Iterate through the top left corner of each square Pseudocode here -> try to work it out yourself! int size = 3; //assume size 3 int R, int C; //from earlier int count; for row = 0 -> R - size for col = 0 -> C – size //row & col: top left corner if isSuperX(row, col, size) increment count Find X

44 Iterating through the sizes of square
For loop! Start and end? Smallest size of square 3 Largest size of square min(numRows, numCols) X Find X

45 Pseudocode Find X maxSize = min(R, C); //for each size
for size = 3 -> maxSize: //for each row for row = 0 -> R - size //for each column in the row for col = 0 -> C – size //row & col: top left corner if isSuperX(row, col, size) increment count Find X

46 Programming Style Find X
Pre-conditions and Post-conditions (5% of overall) Above every method Describe what method is used for Explain its parameters, and what it returns Pre-condition: conditions that must be met before algorithm is called Post-condition: conditions that must be met after algorithm is called Find X

47 Find X /** *Checks if the square in the map is a super X *
*Pre-condition: rowNum and colNum are the row and *column of the top left hand corner of the square. *size is the width of the square. rowNum, colNum, *rowNum+size-1 and colNum+size-1 are within the map *Post-condition: Returns true if both diagonals of the square are X **/ boolean isSuperX(int rowNum, int colNum, int size) { …. } Find X

48 Programming Style (for Sit-In Labs)
Meaningful comments to explain how your algorithm works Iterating through the centre of the square? Iterating through the top left corner of the square? Don’t just use 1 main method Incremental programming Solve each sub-problem one at a time in a separate method Meaningful variables Only use single characters for variables given in the input format or for loop variables Find X

49 In summary Spend some time understanding and formulating your approach to the problem Break down the main problem into sub-problems Iterating through different sizes Iterating through the squares of each size Check if square is a super X Try to understand what the definition is What exactly is a super X? A square with both diagonals of only X Find X

50 End Of File Any Questions?


Download ppt "CS1020 – Data Structures And Algorithms 1 AY Semester 2"

Similar presentations


Ads by Google