data type review structured data types abstraction collection © john urrutia, 2011 all rights...

49
Data Structures & Algorithms Data Type Review Structured Data Types Abstraction Collection © John Urrutia, 2011 All Rights Reserved

Upload: bathsheba-ray

Post on 13-Dec-2015

218 views

Category:

Documents


2 download

TRANSCRIPT

  • Slide 1

Data Type Review Structured Data Types Abstraction Collection John Urrutia, 2011 All Rights Reserved Slide 2 Data & Variables C# is a strong typed language Actions on data is based on the type of data Interaction between different types require conversion to a common type All Data Types fall into 2 major groups that determine how the data can be accessed Value Types Reference Types John Urrutia, 2011 All Rights Reserved Slide 3 Data & Variables Value Types Uniquely identified by a variable name Allocates storage at compile time may also be initialized at compile time Have 4 type sub-categories simple, enumerated, structured, nullable When passed as a parameter a copy of the data is created automatically John Urrutia, 2011 All Rights Reserved Slide 4 Data & Variables simple value data types: Integral types unstructured Signed: sbyte, short, int, long Unsigned: byte, ushort, uint, ulong Floating point types floating point: float, double Special types Boolean: bool Unicode characters: char John Urrutia, 2011 All Rights Reserved Slide 5 Data & Variables CategoryBitsTypeRange/Precision Signed integral 8sbyte128...127 16short32,768...32,767 32int2,147,483,648...2,147,483,647 64long9,223,372,036,854,775,808 9,223,372,036,854,775,807 Unsigned integral 8byte0...255 16ushort0...65,535 32uint0...4,294,967,295 64ulong0...18,446,744,073,709,551,615 Floating point 32float1.5 10 45 to 3.4 10 38, 7-digit precision 64double5.0 10 324 to 1.7 10 308, 15-digit precision Decimal128decimal1.0 10 28 to 7.9 10 28, 28-digit precision John Urrutia, 2011 All Rights Reserved Slide 6 Data & Variables Value Data Types are further sub-divided into enum types Are User Defined enum Distinct type with named constants. Each has an underlying type, which must be one of the eight integral types. The set of values of an enum type is the same as the set of values of the underlying type. John Urrutia, 2011 All Rights Reserved Slide 7 Data & Variables Value Data Types are further sub-divided into struct types Are User Defined struct Similar to class type Represents a structure with data and function members. Do not support user-specified inheritance Implicitly inherit from type object. John Urrutia, 2011 All Rights Reserved Slide 8 Data & Variables Value Data Types are further sub-divided into nullable types Extensions of all other value types with a null value Declaration implied Identified with the ? I.E. int? is a type that can hold any 32 bit integer or the value null. John Urrutia, 2011 All Rights Reserved Slide 9 Data & Variables Reference Types Allocates storage and is referenced by its storage address Identified by variable names which are really the address (multiple identifiers possible) May be initialized at compile time John Urrutia, 2011 All Rights Reserved Slide 10 Data & Variables Reference Data Types are further sub-divided into: Pre Defined array types User Defined class types interface types delegate types John Urrutia, 2011 All Rights Reserved Slide 11 Data & Variables class types Data structure that combines state (fields) actions (methods and other function members) Dynamically create instances / objects. Supports inheritance and polymorphism mechanisms whereby derived classes can extend and specialize a base class. John Urrutia, 2011 All Rights Reserved Slide 12 Data & Variables interface types Defines a contract that can be implemented by class or struct data types Can contain methods, properties, events, and indexers Specifies class or struct members to be supplied that implement the interface. Doesnt provide member implementations John Urrutia, 2011 All Rights Reserved Slide 13 Data & Variables array types An array is a data structure that contains a number of variables that are accessed through computed indices. The variables contained in an array, also called the elements of the array, are all of the same type, and this type is called the element type of the array. John Urrutia, 2011 All Rights Reserved Slide 14 Data & Variables delegate types Represents references to methods with a particular parameter list and return type. Delegates make it possible to treat methods as entities that can be assigned to variables and passed as parameters. Delegates are object-oriented and type-safe. John Urrutia, 2011 All Rights Reserved Slide 15 The class Data Type class is a user defined data type consisting of a header and a body Header Optional - attributes, modifiers, partial Required - class identifier Optional - type-parameter-list, class-base, type-parameter-constraints-clauses Body Required - {} Optional - ; John Urrutia, 2011 All Rights Reserved Slide 16 The class Data Type class modifiers KeywordMeaning new The new operator is used to create new instances of types. abstract Creates a virtual class member that is incomplete and must be implemented in a derived class. sealed Prevent the inheritance of a class or certain class members that were previously marked virtual. static Makes the member part of the Data Type not of the instance John Urrutia, 2011 All Rights Reserved Slide 17 The class Data Type AccessibilityMeaning public Access not limited protected Access limited to this class or classes derived from this class internal Access limited to this program protected internal Access limited to this program or classes derived from this class private Access limited to this class class accessors John Urrutia, 2011 All Rights Reserved Slide 18 The class Data Type class body contain members function members define actions done to the state of the class data members define the variables upon which the function members act. John Urrutia, 2011 All Rights Reserved Slide 19 class Example Define a class, clockType, to implement the time of day in a program. Time is represented as a set of three integers: one to represent the hours, one to represent the minutes, and one to represent the seconds. Perform the following operations on the time: 1. Set the time. 2. Return the time. 3. Print the time. 4. Increment the time by one second. 5. Increment the time by one minute. 6. Increment the time by one hour. 7. Compare the two times for equality. John Urrutia, 2011 All Rights Reserved Slide 20 class Example Some members of the class clockType will be private ; others will be public. Any member that needs to be accessed outside the class is declared public ; any member that should not be accessed directly by the user should be declared private. The user should be able to set the time and print the time. Therefore, the members that set the time and print the time should be declared public. John Urrutia, 2011 All Rights Reserved Slide 21 The class clockType has seven function members: setTime getTime printTime incrementSeconds incrementMinutes incrementHours equalTime. It has three data members: hr min sec The three data members hr, min, and sec, are private to the class and cannot be accessed outside the class. The seven function members can directly access the data members ( hr, min, and sec ). Slide 22 public class clockType { private int hr, min,sec; public int hours//Hours property { get{return hr;} } public int minutes//Minutes property { get{return min;} } public int seconds//Seconds property { get{return sec;} } public void getTime(out mHr, out mMin, out mSec) {mHr = hr; mMin = min; msec = sec; } public void printTime() { Console.WriteLine(The Time is {0:##}:{1:##}:{2:##}", hr,min,sec); } public void incrementSeconds() { sec++; if(sec > 59) { incrementMinutes(); sec = 0; } Slide 25 public void incrementMinutes() { min++; if(min > 59) { incrementHours(); min = 0; } public void incrementHours() { hr++; if(hr > 23) { hr = 0; } Slide 26 public bool equalTime(const clockType ref otherTime) { if( otherTime.hours == hr && otherTime.minutes == min && otherTime.seconds == sec ) return true; else return false; } Slide 27 Collections Abstract concept Structured data type No specific data type but defines a generic set of fields and methods. Each object must be of the same type Generic CRUD methods Create Read Update Delete Slide 28 Collections Collections can be Linear ie. Shopping list Ordered each element follows the previous Starting / Ending elements Non-Linear ie. Organization Chart Structured but no specific order Slide 29 Collections Basic methods Add() Insert() Remove() Clear() Contains() IndexOf() Slide 30 Collections Accessing Collection Elements Direct Access Using a specific Key to access any element Sequential Access Start at the beginning and continue, in order, to the end Slide 31 Collections Sequential Access Collections Start at the beginning and continue, in order, to the end Linear Lists Unordered Ordered Stacks Queues Indexed collections Hash Tables Dictionaries Slide 32 Collections Hierarchical Collections Trees Each element is called a node Each element may have a predecessor and/or successor along with the data being stored. Parent Child relationship Directory Structures Binary Trees Heaps Slide 33 Collections Group Collections Sets An unordered group of unique elements Methods intersection, union Graphs nodes and edges Methods - traversals Networks Specialized graph where each edge is weighted Slide 34 Collections - implementation public class Collection : CollectionBase { public void Add(object item) { InnerList.Add(item); } public void Remove(object item) { InnerList.Remove(item); } public new int Count() { return InnerList.Count; } public void Clear() { InnerList.Clear(); } Slide 35 Collections - implementation class CollectionProgram { static void Main(string[] args) { Collection names = new Collection(); names.Add("John"); names.Add("Thomas"); names.Add("Ethan"); names.Add("Imani"); Console.WriteLine("Writing names added to ArrayList"); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); names.Remove("John"); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); names.Clear(); ListNames(names); Console.WriteLine("Number of names:" + names.Count()); } static void ListNames(Collection col) { foreach (Object i in col) { Console.WriteLine(i); } } Slide 36 Generic Programming Allows you to create a method that will work for all data types. Use of a placeholderfor the data type Data type is resolved at compile time Slide 37 The infamous swap( ) Problem how many methods would you need to write to handle all of the integral data types? Answer: A lot. But by using generic definitions you only need one. Slide 38 Declaration static void swap (ref T val1, ref T val2) { T temp; temp = val1; val1 = val2; val2 = temp; } Slide 39 Implementation Static void Main() { int x=100, y=200; Console.WriteLine( x={0} y={1},x,y); swap (ref x, ref y) Console.WriteLine( x={0} y={1},x,y); } Slide 40 A Stitch in Time Many times it is important to evaluate the efficiency of your code. The timing class will help answer this question. The.NET environment is unpredictable in terms of internal processes Important to isolate timing for just your code. Slide 41 The Timing Class namespace TimerClass { public class Timing { TimeSpan startingTime, duration; public Timing() { startingTime = new TimeSpan( 0 ); duration = new TimeSpan( 0 ); } Slide 42 The Timing Class namespace TimerClass { public class Timing { public void StopTime() { duration = Process.GetCurrentProcess().Threads[ 0 ]. UserProcessorTime.Subtract(startingTime); } Slide 43 The Timing Class namespace TimerClass { public class Timing { public void StartTime() { GC.Collect(); GC.WaitForPendingFinalizers(); startingTime = Process.GetCurrentProcess().Threads[ 0 ]. UserProcessorTime; } Slide 44 The Timing Class namespace TimerClass { public class Timing { public TimeSpan Result() { return duration; } Slide 45 Timing Class Implementation class Program { static void Main(string[] args) { int[] nums = new int[ 100000 ]; BuildArray(nums); Timing tObj = new Timing(); tObj.StartTime(); DisplayNums(nums); tObj.StopTime(); Console.WriteLine( "Time (.NET):{ 0 }", tObj.Result().TotalSeconds); } Slide 46 Timing Class Implementation static void BuildArray(int[] arr) { for (int i = 0 ; i < 100000 ; i++) arr[i] = i; } static void DisplayNums(int[] arr) { for (int i = 0 ; i < 100000 ; i++) Console.WriteLine(arr[i]); } Slide 47 The Stopwatch Class using System.Diagnostics; Stopwatch swTimer; Slide 48 The Stopwatch Class Method NameDescription GetTimestamp() Gets the current number of ticks from timer. Reset() Stops interval and resets elapsed time to zero. Restart() Stops current timing & begins again at zero Start() Starts, or resumes, time measurement. StartNew() Initializes new instance, starts measuring elapsed time. Stop() Stops measuring elapsed time for an interval. Slide 49 The Stopwatch Class Property NameDescription Elapsed Gets the total elapsed time measured by the current instance. ElapsedMilliseconds Gets the total elapsed time measured by the current instance, in milliseconds. ElapsedTicks Gets the total elapsed time measured by the current instance, in timer ticks. IsRunning Gets a value indicating whether the Stopwatch timer is running.