Computational Thinking Problem Solving and Programming IB COMPUTER
Computational Thinking, Problem Solving and Programming IB COMPUTER SCIENCE TOPIC 4
Could you create this pattern using Turtle graphics? ?
Review Instructions • Limited vocabulary (you cannot talk to the computer in plain English…yet) • Sequence (you have to get the order of instructions right) • Looping (same few lines of code over and over) • Store procedures (naming a set of instructions for later reuse by you, or others) • Extending the language (creating a command, e. g. “square”, that didn’t exist before) A computer program is a sequence of instructions writhiten in a limited vocabulary that when executed carry out a specific task on a computer. Computer programs often do repetitive work, such as processing all items in a list, and so they contain features for re-using instructions so that those instructions don’t have to be written multiple times. Loops achieve this aim, a s does the facility to store and name sets of instructions. Stored, named sets of instructions are variously known as procedures, subroutines, functions or methods, depending on the context. In allowing you to creae and save your own procedures, programming languages make themselves extensible. •
Trace these programs (Study them and work out what they do)
Review • • • In the All-rounders burger joint, everyone is trained to do absolutely everything. They can all lmake the burgers, clean the bathrooms, and do the finance, but training takes a long time and none of them are really good at any of these tasks. If the One-job burger joint, each employee has a very specific job. One person makes ”Superburgers, ” one person makes “Megaburgers, ” another person makes “Gigaburgers, ” etc. They are all extremely good at their jobs, but they often find themselves withd nothing to do. If you were running a burger joint, how would your approach differ from All-rounders and One-job?
Review • Create a procedure to make a small square • Create another to make a medium-sized square • Create another to make a big square • Now change your procedures so that they make rectangles instead • What do you find you are having to do? • What seems inefficient about it?
Questions • What problems did you face in the last example? • Which burger joint model is this similar to? • What feature of Logo do you wish existed to overcome the problems associated with this model? (clue: it does exist, for all languages)
Looping and Parameter Passing • An example in Logo • You can pass more than one parameter • Challenge: Make one single procedure that draws any regular polygon of any size
Practice using the repeat statement and passing parameters Write procedures to create each of the following patterns. Try to program them as elegantly as possible! That means using loops and parameters.
Generating Complexity • Abstraction makes it easy to generate complex patterns quickly.
Recap • Parameters / arguments • • These are values that are given to a procedure so that it knows how to performs its task. Specialization versus generalization • Your procedures should be able to perform the same task in a number of different ways according to the parameters. • Procedures should not be too specific, e. g. square 10, square 20, etc. , and they should not be too general, e. g. draw. ALine.
Your task is to make this pattern in Logo
Put a stake in the ground • • • Paste in a screenshot of the repeating pattern from the last slide. Include your code and a few paragraphs. Where did you spot repeating patterns? How did you decide what procedures to create? In general, what are the advantages of loop structures? What are the advantages of creating sub-procedures? Imagine that your code is going to be used by a flooring company to produce a pattern for any size of floor. • • What parameters could you allow your customers to set? How would these affect your code?
Logo Challenge Write a Logo one-liner using 15 or fewer words, not counting square brackets and parentheses, to produce the most beautiful, complex, and interesting picture.
Computational Thinking • Open the IB guide • Five different types of Computational Thinking. • Find out what they are. • Add them to your website.
Example • You have decided to invite your friends over to watch the big basketball game. You are going to do a barbecue for everyone. • How will you use computational thinking to make sure your day does well? • In groups, think of examples of where you can apply each of the five types of computational thinking to this situation.
Thinking… Examples in the basketball game task Ahead Checking the time difference and making sure you get the time of game right. Is daylight savings time applied? Procedurally Checking that the game is televised before sending out the invitations. Finding out who is coming before buying food. Logically If…then… If more than 20 people come then you will need more chairs. Abstractly Generalization. Considering the main points without dealing with details. light the barbeque, get everyone sat down in front of the game, cook and serve the food. Concurrently Saving time by doing a number of jobs at the same time. Prepare the food while the barbeque is warming up. Serve the drinks while the food is cooking. Recursively Ask friends to invite their friends.
Thinking Ahead • Think back to the basketball game task. • In what ways did you need to think ahead? • What examples of thinking ahead do you know of from the world of computing?
Pre-conditions and post-conditions • A method of specifying what a procedure accomplishes without going into the details of how it works. This helps other developers to predict how the function will behave and how to use it properly. Go and wr ite me a function. I don’t care how you d o it, just make sure these requireme nts ar met.
Example Void print_sqrt (double d) { // pre-condition: d>=0 //post-condition: sqrt(d) written //to standard output } You should add these comments to every non-trivial method that you write in your Java IA
Pre- and post-conditions help programmers to work together by making it clear how a function will behave before it is used. They also help to eliminate bugs and improve the reliability of software. Your job is to function. W write the hen I call it , I will ensu re that the pre-condit ions are m et. OK. As lon g as you meet the p reconditions , I guarantee it will work. But just to be on the safe side my function will check if a pre-condition has been violated, and report an error if it has.
Conditions to Decisions • IB documentation wants you to realize that pre- and post-conditions affect the decisions that will be made in the implementation of the functions • Think back to the sqrt() function • Give an example of an if… then… Decisions block that will follow from the preconditions.
Your turn • You design a function double reciprocal (int x) that takes an integer argument x and returns the reciprocal • What are the pre- and post-conditions?
Gant charts Decompositions in subtasks. Thinking procedurally, thinking ahead, thinking concurrently.
Review • What are the five types of computational thinking?
Concurrent thinking in everyday life • • I’ve got to wash my jeans and cook dinner Things to do: • • • Put the jeans into the washing machine and turn it on Take the jeans out of the washing machine and hang them up Put the food into the oven Take the food out of the oven What order is best? Why?
Thinking concurrently • What examples of concurrent thinking can you think of from the world of computer science? • Multi-tasking OS • Time-slicing • Scheduling • Interrupts • RDBMS (database) • transactions
Dining Philosophers • Philosophers like to think a bit, eat a bit, think a bit, etc. • Need two chopsticks to eat • Have to pick them up one by one • Can’t steal them from someone
Thinking Abstractly • A publication • A newpaper • Arizona Daily Star • The May 18 edition of the Arizona Daily Star • My copy of the May 18 edition of Arizona Daily Star as it was when I first picked it up (as contrasted with my copy as it was a few days later: in my fireplace burning) Arizona Daily Star
Abstraction • • • Considering the same object from different viewpoints Different aspects of the object are important to different audiences Describe a car from the view point of: • • A driver A mechanic A physicist What are the benefits of abstraction? How does it help us? • • • Presents only relevant information Hides potentially confusing detail Allows us to build systems of arbitrary complexity
Task: The OSI Model and abstraction • Write a brief outline of how the OSI Model uses abstraction. • How does it make complex task simple? • What does each layer know about the one below? • What does each packet know about its payload? • Imagine you are Ms. Bulleigh and you want to send a letter to the superintendent of Amphi USD, Mr. Jaeger. What layers of abstraction exist to facilitate this process? • Describe them and explain why they are useful.
Flowcharts
Task • Flowchart for finding a given value in an array
Task: Produce a trace table • HTTPS: //WWW. 101 COMPUTING. NET/USING-TRACETABLES/
Basic Operations in Pseudocode Assume array A exist and has 100 elements. Construct code to add 1 to each item in the array. loop i from 0 to 99 A[i] = A[i] + 1 end loop Notice that: • Variable names are capitalized • Arrays are subscripted using square brackets • There are no curly braces • Keyboards are lower case • Arrays are zero-based and so traversals run from 0 to length – 1 • The question will always give you enough information
Miscellaneous algorithms Construct code to determine whether an array is sorted (ascending) or not. Construct code to determine whether a sorted array is consecutive or not (i. e. {4, 5, 6, 7} is consecutive {4, 6, 9, 12}. Construct code to determine whether an array is a palindrome (i. e. the same backwards as forward). In a large array of integers, every element is duplicated except one, e. g. {1, 1, 2, 2, 3, 3, 4, 4, 5, 5, etc. }. Construct code to find which is not duplicated. A and B are two sorted arrays (ascending order). Construct a code to merge them into array C. (You may assume that C has the correct dimensions. ) A sorted array A contains some duplicate values. Construct code to remove the duplicates. (This should be done “in place, ” i. e. you are not allowed to create a new array. ) Contruct a code to turn an array NUMS into a cumulative list numbers (e. g. 1, 3, 4, 5, would become 1, 4, 8, 13). Construct code to reverse this process.
Random sample data Data sets can be useful and hard to find, but you can make them up using a computer program… Write an algorithm that outputs a table of distances between cities. You will need to create random corrdinates for each city and then use Pythagoras’ Theorem to calculate the distance between them. The number of cities and the dimensions of the coordinate plane should be set as parameters.
Quiz (next slide) • Constructing pseudocode • Including ifs, nested ifs, Boolean conditions, loops, nested loops, arrays. • Interpreting pseudocode • Interpreting flowcharts
Questions An array NAMES holds the names of all 200 students in grade 11. Another array SCORES contains 200 test scores. The arrays are parallel, such that NAMES[X] and SCORES[X] contain data about the same student. 1. Construct pseudocode to output the maximum score [3 marks] 2. Construct pseudocode to output the names of the students who scored above 80. [4 marks] 3. Construct pseudocode to output the lowest three scores. [5 marks]
Standard Algorithms • Sequential search • Binary search* • Bubble sort • Selection sort • Insertion into the middle of an array • Deletion from the middle of an array If you can code these alogorithms from scratch then you are very well prepared for the SL exam. *SLs don’t need to code binary search, but they need to understand under what circumstances it can be used. There are two key characteristics of data structures that can take advantage of binary search…
Assembly Tutorial • http: //skilldrick. github. io/easy 6502/ HTTPS: //EN. WIKIPEDIA. ORG/WIKI/X 86_INSTRUCTION_LISTINGSFUNDAMENTAL OPERATIONS OF A COMPUTER: LOA: Load data from memory address STO: Store data at memory address ADD: Add SUB Subtract JMP: Jump to new memory address and execute from there CMP: Compare (Conditional JMP etc. These are Assembler instructions. They constitute the simplest programming language intelligible by humans. These instructions are still not intellible by the CPU itself and so must be converted into machine code (binary). These vary depending on the chip. Here are the instructions for the x 86 (intel) family of chips.
Fundamental vs Compound Operations The fundamental operations of a computer are the ones in the CPU’s instruction set. An instruction set generally has in the order of tens to a few hundred instructions. (This is the instruction set for the original 8086 processors. ) Each of these fundamental operations can be executed in one fetch-execute cycle. Some examples are given in the previous slide. Compound operations are those that we think of as a single operation, but which in reality are made up of more than one (usually many more than one) fundamental operations. An example of a compound operation is sorting list, or finding the maximum value in a list, etc. There may just be one statement or line of code, as in Java’s array. List. sort() or Python’s max(list) but they are both composed of a large number of fundamental operations.
Watch this excellent short video
High and low level languages High-level languages are designed to be understood by humans. Low-level languages require greater understanding of computer hardware. The lowest level language – machine code (i. e. binary) – is almost impossible for humans to understand, but is perfect for the CPU. High-level languages are: • More like human language • Easier to read and understand • Portable from one computer to another (generally) Seriously, watch this excellent short video
Ways in which high-level languages differ Keywords Each language has its own set of reserved words. A very similar set is used in C, C++, Java and Javascript but that set is quite different from those used in BASIC or __________ Syntax Typing Strong typed: Values have a type which cannot change, e. g. Java, Python. Weakly typed. Values can be interpreted in different ways. Java is an example of a statically, strongly typed language, i. e. one in which you have to explicitly declare what data type your variables are: Compilation vs. Interpretation Paradigm Purpose
4. 1. 3 Explain the role of sub-procedures in solving a problem • Sub-procedures, sub-routines, sub-programs, functions, methods, etc. – same idea • Breaking large problems down into simpler units is a fundamental programming concept • Advantages are: • Smaller problems are simpler to solve • Reduces duplicate code • Allows code to be reused • Allows different people to work on one project because tasks can be divided up • Hides confusing implementation (do you know how a car engine works? • Identifiers (method names) make code easier to trace and understand)
4. 1. 4 Identify when decision-making is required in a specified situation (2) 4. 1. 5 Identify the decisions required for the solution to a specified problem (2) 4. 1. 6 Explain the relationship between the decisions and conditions of a system (3) 4. 1. 7 Deduce logical rules for real-world situations (3) These seem to refer to skills that you will need to be able to use during exam questions.
For loop practice The test scores of 100 students are held in an array SCORES. 1. Construct pseudocode to output the minimum score. 2. Construct pseudocode to output the number of scores above 50. 3. Construct pseudocode to output the average score. 4. Construct pseudocode to count the number of scores that lie between 50 and 80. (See if you can code two solutions to this, one using Boolean operators and one using nested ifs. ) 5. Construct pseudocode to output the top three scores. It would be a good idea to put these questions, and your code, up on your google site.
Insertion into an array • • Sorted ARRAY of 100 elements. Only the first ENTRIES are populated. Insert N into the correct place of the array. Break the problem down • Find the target index • Shift all the entries from the target index to the end of the array up one place • Put N into the array Write pseudocode Explain why insertion into an array is problematic (reference to static data structures)
Sorting Algorithms https: //www. freecodecamp. org/news/sorting-algorithmsexplained/
Dice task (possible solution) Subprocedure 1: roll(n). Rolls a dice and returns the number of sixes. Subprocedure 2: all. Sixes(n): Calls roll(n) repeatedly until it returns n (i. e. all dice were sixes). Returns the number of calls necessary. Subprocedure 3: do. Trials(t, n): calls all. Sixes(n) t times and returns the average. Main: Ask the user for the number of dice n and number of trials t, calls do. Trials(t, n) and reports the result to standard output.
Airline Seat Booking
- Slides: 74