Simplifying Flow of Control

Slides:



Advertisements
Similar presentations
Introduction to C Programming
Advertisements

SYMBOL TABLES &CODE GENERATION FOR EXECUTABLES. SYMBOL TABLES Compilers that produce an executable (or the representation of an executable in object module.
Copyright 2003Curt Hill Hash indexes Are they better or worse than a B+Tree?
Copyright © 2007 Pearson Education, Inc. Publishing as Pearson Addison-Wesley Slide 4- 1.
Java Unit 9: Arrays Declaring and Processing Arrays.
CPS120: Introduction to Computer Science Arrays. Arrays: A Definition A list of variables accessed using a single identifier May be of any data type Can.
Lists in Python.
CS212: DATA STRUCTURES Lecture 10:Hashing 1. Outline 2  Map Abstract Data type  Map Abstract Data type methods  What is hash  Hash tables  Bucket.
Copyright Curt Hill Tries An N-Way tree with unusual properties.
1 Compiler Construction (CS-636) Muhammad Bilal Bashir UIIT, Rawalpindi.
I Power Higher Computing Software Development High Level Language Constructs.
CPS120: Introduction to Computer Science Lecture 15 Arrays.
Copyright Curt Hill The C/C++ switch Statement A multi-path decision statement.
Copyright Curt Hill Arrays in C/C++ More on usage.
Programming Fundamentals. Overview of Previous Lecture Phases of C++ Environment Program statement Vs Preprocessor directive Whitespaces Comments.
CPSC 252 Hashing Page 1 Hashing We have already seen that we can search for a key item in an array using either linear or binary search. It would be better.
Copyright © Curt Hill Hashing A quick lookup strategy.
ITP © Ron Poet Lecture 6 1 More on if. ITP © Ron Poet Lecture 6 2 Remembering Tests  We often want to remember the result of a test, so that we can use.
Copyright © 2014 Curt Hill Algorithms From the Mathematical Perspective.
Chapter 2 Variables and Constants. Objectives Explain the different integer variable types used in C++. Declare, name, and initialize variables. Use character.
Copyright © Curt Hill The C++ IF Statement More important details More fun Part 3.
The for Statement A most versatile loop
CS203 Lecture 14. Hashing An object may contain an arbitrary amount of data, and searching a data structure that contains many large objects is expensive.
N5 Databases Notes Information Systems Design & Development: Structures and links.
Invitation to Computer Science, C++ Version, Fourth Edition
Week 2 - Wednesday CS 121.
18. Table-Driven Methods CSC-3004 Introduction to Software Development
Java Language Basics.
CHP - 9 File Structures.
A bit of C programming Lecture 3 Uli Raich.
Selection (also known as Branching) Jumail Bin Taliba by
Control Structures Combine individual statements into a single logical unit with one entry point and one exit point. Used to regulate the flow of execution.
More important details More fun Part 3
Chapter 4: Making Decisions.
Department of Computer Science,
LEARNING OBJECTIVES O(1), O(N) and O(LogN) access times. Hashing:
A Very Common Series of Techniques
Are they better or worse than a B+Tree?
Other Kinds of Arrays Chapter 11
Other Kinds of Arrays Chapter 11
Chapter 4: Making Decisions.
JavaScript: Functions.
Chapter 5: Arrays: Lists and Tables
While Loops BIS1523 – Lecture 12.
Tries A trie is another type of tree structure. The word “trie” comes from the word “retrieval,” but is usually pronounced like “try.” For our purposes,
IPC144 Introduction to Programming Using C Week 2 – Lesson 1
Introduction to Python
Hash Tables.
A Kind of Binary Tree Usually Stored in an Array
Arrays in Java What, why and how Copyright Curt Hill.
Fundamentals of Data Structures
A Robust Data Structure
Topics 4.1 Relational Operators 4.2 The if Statement
Data Types and Data Structures
CIS162AD - C# Arrays ch08.ppt.
Advance Database System
Advanced Implementation of Tables
The Java switch Statement
Spreadsheets, Modelling & Databases
PowerShell Flow of Control Copyright © 2016 – Curt Hill.
Instructions in Machine Language
How to use hash tables to solve olympiad problems
Programming Logic and Design Fifth Edition, Comprehensive
This is not an advertisement for the profession
Tree A tree is a data structure in which each node is comprised of some data as well as node pointers to child nodes
Variables and Constants
While and Do While Syntax, semantics and examples
Presentation transcript:

Simplifying Flow of Control Table Driven Logic Simplifying Flow of Control Largely extracted from Code Complete by Steve McConnell Copyright © 2016 Curt Hill

Introduction The idea here is to consider a number of table techniques to reduce the programming logic of a module The table lookup will replace a number of if and/or switch statements If we can apply these ideas it will make our code simpler and easier to understand Usually faster as well Copyright © 2016 Curt Hill

Roots Prior to your existence the IBM 360 had a translate instruction It was used to translate one character set into another, among other things What you had was a table of 256 characters You used a character as a subscript into this table It then found the corresponding character Copyright © 2016 Curt Hill

Example IBM 360s used EBCDIC, but they often had to deal with ASCII characters from other machines Suppose we have an ASCII file Load a table with EBCDIC characters in their ASCII positions Then use each ASCII character as a subscript into this table The file is then translated from ASCII to EBCDIC Copyright © 2016 Curt Hill

Parts of this table 32 blank 33 ! 34 “ 35 # 36 $ 37 % 38 & 46 . 47 / Position Character 32 blank 33 ! 34 “ 35 # 36 $ 37 % 38 & Position Character 46 . 47 / 48 49 1 50 2 51 3 52 4 Position Character 60 < 61 * 62 > 63 ? 64 @ 65 A 66 B Table would only need to be 128 characters ASCII blank is 32, EBCDIC blank is 64 Copyright © 2016 Curt Hill

Continuing The IBM 360 is largely dead and gone except for museum pieces The technique continues Copyright © 2016 Curt Hill

Issues We need to be concerned about two issues How to look up entries? What should be stored in the table? Then we can consider three approaches Direct access Indirect access Stair-step access Then we will know it all We hope Copyright © 2016 Curt Hill

Direct Access Tables A direct access table allows a direct lookup from part or all of the data The IBM 360 character translate is an example Typically we have an integral item and we can adjust its range into the subscript Looking up month names is also a simple example Copyright © 2016 Curt Hill

Month Name Lookup In any of many Date objects you saw code like this: switch(month){ case 1: name = “January”; break; case 2: name = “Febuary”; break; case 3: name = “March”; break; … } This works but what does it do to the complexity and LOC? Even uglier than nested ifs Copyright © 2016 Curt Hill

Month Name Lookup Again Instead try this: String months[] = {“January”,“Febuary”, “March”, … }; … name = months[month-1];} This is much simpler There are many other sorts of subscript adjustments Such as this month-1 Copyright © 2016 Curt Hill

Number of Days This could get somewhat more complicated if we wanted number of days in a month We would have a table of numbers We would need one if following the assignment that checked if it was February and a leap year This would still be easier than the switch seen in the Date class Copyright © 2016 Curt Hill

Dimensionality There is no reason why the table has to be a single dimension We may end up with an array of several dimensions We may use several types of variables and adjust each one in a separate way Copyright © 2016 Curt Hill

Insurance Rates Suppose we want to lookup driver’s insurance rates The factors that we might consider would be: Age Gender Marital status The lookup could be a complicated collection of decision statements or: rate = rats[age][gender][ms]; Copyright © 2016 Curt Hill

Practicalities This one would be better read in at program startup This allows rates to change over time Whether gender and marital status are enumerations or Booleans is irrelevant Both map into zero based values The lowest driving age may need to be subtracted from the age of the client to make that zero based Copyright © 2016 Curt Hill

Lookup Keys with Issues There are many potential keys that do not map onto zero based integers very well In the insurance rate example we would have to eliminate ages less than 16 (or so) We also want to collapse ranges of rates There is not much difference between a driver of age 34 and one of age 35 In these cases we use a function to transform the key This key transformation is not hashing although it sounds like it in some ways Copyright © 2016 Curt Hill

Indexed Access Tables Often it is difficult to do the transformation It is not a case of simple mathematical operations such as subtraction and division In these situations we use two tables The first is the table of indices The second is the table of data Particularly good when the data is much larger than the index Copyright © 2016 Curt Hill

Indexed Picture Index table Data table Usually close to full Could be quite sparse Copyright © 2016 Curt Hill

Commentary Although you could use a hash in this case this not usually the idea What you usually have is numeric key but it is sparse Consider products that have a four digit product number, but there are currently only 200 of them We do not mind wasting space in the index table, but a data table entry consumes a lot more space The index table could be pointers as well Copyright © 2016 Curt Hill

VLookup Recall the VLookup function of Excel This is a rectangle of two rows and several columns We take a value and find its row in the first column and then use the value in the second column This is routinely how a letter grade is computed in spreadsheets Copyright © 2016 Curt Hill

Grades with Decisions You probably remember something like this: if(grade< .6) s = “F”; else if(grade < .7) s = “D”; else if(grade < .6) … We can do this with a Stair-Step Table Copyright © 2016 Curt Hill

Stair-Step Tables The idea is a two column array First column has the maximum (or minimum) value of that range Second column the lookup value The ranges do not have to be equal sized If we read the data from disk, we can change sizes without changing the code Copyright © 2016 Curt Hill

Example typedef struct { float value; BigClass data;} entry; entry table[50]; int size; float val; BigClass result; … for(int i = 0;i<size;i++){ if(val < table[i].value){ result = table[i].data; break; } Copyright © 2016 Curt Hill

Finally Table driven methods can increase flexibility, while reducing code The trick is to find the right type of table and the right type of initialization Copyright © 2016 Curt Hill