CS1020 – Data Structures And Algorithms 1 AY Semester 2

Slides:



Advertisements
Similar presentations
1 Various Methods of Populating Arrays Randomly generated integers.
Advertisements

08 Deterministic iteration1May Deterministic iteration CE : Fundamental Programming Techniques.
Nested Loops. Nested loops Just as a selection structure can be nested within another selection structure (or within a loop), a loop can also be nested.
CSE 1301 Lecture 6B More Repetition Figures from Lewis, “C# Software Solutions”, Addison Wesley Briana B. Morrison.
CS 106 Introduction to Computer Science I 01 / 30 / 2008 Instructor: Michael Eckmann.
Introduction to Computers and Programming Lecture 8: More Loops New York University.
Introduction to Computers and Programming for Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course. Introduction to.
Introduction to Computers and Programming More Loops  2000 Prentice Hall, Inc. All rights reserved. Modified for use with this course.
Copyright 2008 by Pearson Education 1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops reading: 4.1, 5.1.
11 Chapter 4 LOOPS AND FILES. 22 THE INCREMENT AND DECREMENT OPERATORS To increment a variable means to increase its value by one. To decrement a variable.
Peter Andreae Computer Science Victoria University of Wellington Copyright: Peter Andreae, Victoria University of Wellington Summary and Exam COMP 102.
CS1020E Sitin 1 Discussion -- Counting Palindromes.
CS303ELoops1 CS 303E Lecture 8: Loops Self-referentially, short for GNU's not UNIX, a Unix-compatible software system developed by the Free Software Foundation.
Applications of Arrays (Searching and Sorting) and Strings
Loops: Handling Infinite Processes CS 21a: Introduction to Computing I First Semester,
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Hello.java Program Output 1 public class Hello { 2 public static void main( String [] args ) 3 { 4 System.out.println( “Hello!" ); 5 } // end method main.
The while Loop Syntax while (condition) { statements } As long condition is true, the statements in the while loop execute.
Programming for Beginners Martin Nelson Elizabeth FitzGerald Lecture 5: Software Design & Testing; Revision Session.
October 28, 2015ICS102: For Loop1 The for-loop and Nested loops.
1 Building Java Programs Chapter 5 Lecture 5-1: while Loops, Fencepost Loops, and Sentinel Loops; Procedural Design reading: 5.1 – 5.2; 4.5.
Chapter 5: Control Structures II J ava P rogramming: From Problem Analysis to Program Design, From Problem Analysis to Program Design,
DT249-Information Systems Research Practice Programming Revision Lecture 2 Lecturer: Patrick Browne.
Scope When we create variables and functions, they are limited in where they are visible and where they can be referenced For the most part, the identifiers.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 12/11/20151.
1 Arrays of Arrays An array can represent a collection of any type of object - including other arrays! The world is filled with examples Monthly magazine:
Sit-In Lab 2 - OOP Restaurant.  Manage a restaurant and perform these types of queries: Assign a favorite table to a specific group Assign the lexicographically-smallest.
Zhen Jiang Dept. of Computer Science West Chester University West Chester, PA CSC141 Computer Science I 2/4/20161.
INVITATION TO Computer Science 1 11 Chapter 2 The Algorithmic Foundations of Computer Science.
Take-Home Lab #02 CS1020 – DATA STRUCTURES AND ALGORITHMS 1 AY SEMESTER 2 1.
Chapter 5 – Part 3 Conditionals and Loops. © 2004 Pearson Addison-Wesley. All rights reserved2/19 Outline The if Statement and Conditions Other Conditional.
CSC 1051 – Data Structures and Algorithms I Dr. Mary-Angela Papalaskari Department of Computing Sciences Villanova University Course website:
CS1020 – Data Structures And Algorithms 1 AY Semester 2
Trace Tables In today’s lesson we will look at:
CSC111 Quick Revision.
Manipulating MATLAB Matrices Chapter 4
Loops.
Chapter 5: Control Structures II
Loop Structures.
CS1371 Introduction to Computing for Engineers
Sit-In Lab 1 Ob-CHESS-ion
User input We’ve seen how to use the standard output buffer
Java Programming: Guided Learning with Early Objects
Counted Loops.
Lecture 07 More Repetition Richard Gesick.
Chapter 5: Control Structures II
TK1114 Computer Programming
LOOPS.
Stack Data Structure, Reverse Polish Notation, Homework 7
Lecture 4B More Repetition Richard Gesick
Repetition Chapter 6 12/06/16 & 12/07/16 1 1
Algorithm Discovery and Design
Defining methods and more arrays
ARRAYS 1 GCSE COMPUTER SCIENCE.
Recursion.
Coding Concepts (Basics)
Building Java Programs
Algorithm Discovery and Design
CS 200 Primitives and Expressions
Module 4 Loops and Repetition 2/1/2019 CSE 1321 Module 4.
Building Java Programs
Java Programming Loops
Suggested self-checks: Section 7.11 #1-11
Building Java Programs
Building Java Programs
Building Java Programs
LOOPS The loop is the control structure we use to specify that a statement or group of statements is to be repeatedly executed. Java provides three kinds.
Building Java Programs
Building Java Programs
Presentation transcript:

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

Problem 1 Measurement

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

How? Data Storing Data Processing Measurement

Array Solution VS Non-Array Solution Measurement

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

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

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

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

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

Problem 2 Island

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

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

? Any Ideas? Island

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

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

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

? 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

Trick Island

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

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

(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

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

Problem 3 Find X

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

End Of File Any Questions?