Modelling and Algorithmization of Data Structures in Engineering Doc. Ing. Pavel Kopeček, CSc. 6.12.2007 1 Objectives: The aim of the course is to provide explanation of dynamic linear and network data structures. This will serve as a theoretical basis for constructing simple models of data structures for engineering purposes and for demonstration of selected problems of planning batches, due dates and prices. You will practise programming in Pascal (Delphi Console Application) and in MS Access. 2 1 Fundamentals of the Theory of Data Structures Objectives: The chapter is aimed at reviewing the essential data types. Keywords: Array; Binary tree; Constant; Construktor; Data structure; File; Group variable; Integer variable; Numerical variable; Real variable; Record; Selector; String; Vector; 1.1 Data Structure Objectives: The goal of this article is to present the definition and classification of data structures. Keywords: Construktor; Data structure; Selector; Data Structure Definition of the Term Data structure is an effective arrangement of elements, parts or components of a block of data according to a certain unifying principle. It is also a system of relationships, rules and limitations for effective organization of components of this block of data. The work with a data structure is classified into logical and physical levels. The logical level is the abstract idea, while the physical level represents its implementation. It is possible to represent the structure in several different ways. For instance, a complex number may be represented in cartesian or polar coordinates. A list can be represented as an array or as linked dynamic variables. The logical level is related to the data structure semantics. The semantics of the data structure governs the following: the process or the instant of generation of the structure the types of operations for handling the existing structure and the structure changes resulting from these operations structure cancellation or termination processes identification of the data structure properties of the data structure Description of a data structure consists of a diagram or a type of a data structure. The diagram of the data structure only occurs once in the system. Definitions of diagrams vary in different programming languages (definitions/declarations of types in structured languages, introduction of a class in object-oriented methods, and others). Specific implemented and used data structures of certain types with their own names are called instances. There may an unlimited number of instances of a single type. 3 The tool for one-time filling particular data in the data structure, we call that tool a constructor. For instance, the array data structure in most programming languages has no constructor. Where the individual elements of the data structure can be accessed for processing, the data structure has a selector. For instance, the data structure “set” has no selector. The selector of an array is an index. The selector for the record data structure is the name of its particular field. Data structures on high abstract levels are very complex. They may even contain parts of code (objects methods of component technology with so-called scripts). Classification of Data Structures Data structures may be classified according to various parameters: The complexity of their structure: Simple data structures (J) - it is impossible to decompose these to simpler elements Structured data structures (Str) - these consist of simpler substructures Homogeneous data structures (H) - all items of the structure are same types Heterogeneous (Nh) - the structure items may be of different types Arrangement of neighbouring items: Linear (L) - it is possible to arrange the neighbouring items of the structure in a sequence with a predecessor/successor order Non-linear (NL) - it is not possible to order the neighbouring items as a sequence Changes to the number of items: Static (Sta) - these exist over the whole processing time Dynamic (D) - these are being generated and terminated during processing time Table shows selected data structures and their properties. 4 Figure 1.1-1 Classification of data structures 1.2 Selected Basic Data Structures Objectives: This article is aimed at demonstrating simple data structures. Keywords: Constant; Integer variable; Numerical variable; Real variable; Selected Basic Data Structures Individual data structures may be described with reference to the following attributes: Abstract concept Semantic meaning Properties Allowed operations Constants Semantic meaning An instance of a certain type having a fixed value over the whole time of its existence. Allowed operations Arithmetic and other operations according to the type. 5 Properties Type, Value Examples: 1 logical constants: true, false 2 character constant: 'A', '$', '1' 3 integer constant: 9,-3 4 real constant: 3.14159, -1.23E-23 5 text constant: 'Tommy’s a rascal' Simple Variables Integer variable. The related abstract concept is shown in the Fig . Figure 1.2-1 Integer variable Semantic meaning The memory location storing the value of the integer number n. The number meets the condition of MIN <= n <= MAX, where MIN,MAX are integer numbers. Properties Name, value, representation, range (depending on language type) Allowed operations arithmetic operations relational operations value assignment testing (even, odd) integer functions Real variable. The related abstract concept is shown in the Fig. . 6 Figure 1.2-2 Real variable Semantic meaning The memory location for storing a real number model in a semilogarithmic form, which meets the condition of MIN <= r <= MAX, has a certain number of valid decimal places and is characterized with a smallest positive number other than zero. Properties Name, value, representation, range (depending on language type) Allowed operations: arithmetic operations relational operations value assignment real variable functions rounding, obtaining the integer part of number Logical (Boolean) Variable The related abstract concept is shown in the Fig.. . Figure 1.2-3 Logical variable Semantic meaning The memory location for storing a variable with the domain of two values (true/false). Properties Name, value, representation Allowed operations: logical operations value assignment logical functions 7 Complex variable The related abstract concept is shown in the Fig. . Figure 1.2-4 Complex variable Semantic meaning Memory location for storing a complex number in its semilogarithmic form. Properties Name, value, representation Allowed operations: arithmetic operations value assignment retrieval of the real and imaginary parts relational operations Numerical Variable. This is a special type used in some database systems or in the Cobol language. The related abstract concept is shown in the Fig. . Figure 1.2-5 Numerical variable 8 Semantic meaning Memory location for storing the sequence of consecutive numerical and special characters ('+','-'), which are allowed to represent a number. Decimal points in rational numbers are typically imaginary. Properties Name, value, length Allowed operations All operations are identical to those used with simple numerical variables. 1.3 Index Variables Objectives: This article describes the work with index variables and strings. Keywords: Array; Matrix; String; Vector; Index Variables Text String The related abstract concept is shown in the Fig. Figure 1.3-1 Text string Semantic meaning Memory location for storing the sequence of consecutive numerical and special characters, which are allowed for use in text. Properties Name, value, length Allowed operations: transfer of the whole or part of string comparison of two strings viewing the string by individual characters concatenation of two strings splitting a string into two strings alteration of a character in a string finding a substring deleting a substring inserting a string into another string 9 and others Note: Strings may be represented in different ways in the memory: ending with a binary zero (C. Delphi) starting with binary length (Pascal standard in Delphi as well). starting with length and the number of uses (Delphi Pascal) One-Dimensional Array - Vector The related abstract concept is shown in the Fig. . Figure 1.3-2 One-dimensional array-a vector Semantic meaning n elements of the same type stored repeatedly in sequence. It is possible to reference them with the order index i <1,n> or <MIN,MAX> (MIN,MAX may be negative values). It is possible for an array item to have internal structure. Properties Name, values of individual items, maximum number of repeating items, item type Allowed operations: assigning a value to a certain item assigning the same value to all items finding the item with a certain value. ordering items according to values of their attributes vector operations for numerical values of vector items Multi-Dimensional Arrays - Two and Higher-Dimensional Matrix The abstract concept is shown in the Fig . 10 Figure 1.3-3 Two-dimensional array - matrix Semantic meaning One-dimensional array, whose item is another one or multi-dimensional array Properties Name, values of individual items, max. number of repeated items in a row, max. number of rows (max. number in other dimensions), type of items Allowed operations: assignment of a value to a certain item assigning the same values to all items finding the item with a certain value ordering items according to values of their attributes vector operations for numerical values of vector items 1.4 Group Variable, Record and File Objectives: This article explains terms such as the group variable, record and file. Keywords: File; Group variable; Record; 11 Group Variable, Record and File Group Variable (Group of Structures) The abstract concept is shown in the Fig. . Figure 1.4-1 Group variable Semantic meaning Several data structures make up a group Unlike array, this is a group of structures of different types The membership in group is typically based on the use of data The group has either an assigned name or a level number The data structures which make up this structure can be group variables themselves Properties Name List of structures making up the group Allowed operations: transfer of a group or of its part setting all group elements to zero value comparison of two groups Note: Some languages may omit some of the operations (e.g. resetting to zero) The level of nesting is usually restricted (e.g. Cobol - 49). Record (Structure, Data Record) The abstract concept is shown in the Fig. . Records are classified into linear ones, which consist of individual, further indivisible items and into hierarchical records (with group variables). 12 Figure 1.4-2 Record Semantic meaning A record is a linear data structure consisting of elements on a logical level. The elements are processed either all at once (I/O operations, transfers) or one at a time. In most cases, the record describes a certain entity type (employee, material, order) or a relationship (material for production of a component). Properties Fixed or variable length of record Number of fields of record Allowed operations: assignment of the whole record to another record resetting the record to zero (assigning the NULL value to each of its fields). input/output operations - reading from the file and writing into it retrieving values of its individual fields changing individual fields Soubor (File) The abstract concept is shown in the Fig. an external memory. . A file is a sequence of records, which is typically stored in 13 Figure 1.4-3 File Semantic meaning Linear set of the record-type data structures It is possible to change the number of components of a file by means of a program (adding and removing components at the file end) The file components are not related and can be processed independently Properties Name (physical name - the name, by which the operating system identifies the file) Identification (logical name - the name, by which the program identifies the file) Organization of the file Access to information (serial or direct access) Types and number of records in the file Allowed operations: assignment of the logical name to the physical one - file identification - e. g. Assign (F1,’List of employees) opening and closing the file - obtaining access to file, testing whether it exists and closing the file reading/writing/changing the content of an existing record appending a new record/deleting an existing record creating an empty file extending the file (resuming the writing operations) copying the file file ordering (based on a sort key) Note: Files in some operating systems may start and end with special records (labels) and special marks (such as typemarks on magnetic tapes). 14 2 Linear Data Structures Objectives: The chapter is aimed at describing linear data structures. Keywords: List; Queue; Stack; 2.1 List Objectives: This article describes the list data structure Keywords: List; List The abstract concept of a list is shown in the Fig. . Figure 2.1-1 List Semantic meaning List is a dynamic linear homogeneous data structure with a variable number of items, represented by a sequence of individual items. List elements are ordered. The list may be empty or may contain items of identical types. Each item of a non-empty list other than the last one will be explicitly assigned one next item. Each item of a non-empty list other than the first one will be explicitly assigned one preceding item. The item of a list being currently processed is the current one. Allowed operations on the list: creating an empty list (initialization of a list) adding a new item after the current item inserting a new item before the current item 15 adding an item to a list and removing an item from the list establishing access to the current item of the list setting the cursor pointing to the current item to the beginning or the end of the list moving the current item to the preceding item moving the current item to the following item testing whether the list is empty testing whether the current item is the first one testing whether the current item is the last one The list is represented in two ways: by array using dynamic variables linked with pointers, forming a linked list Figure 2.1-2 Representation of a list using an array Representation using an array requires a sufficiently large array. Control variables are associated with this array, containing the index of the last occupied array item (L), the length of the reserved array (M) and the current item index (C). The representation of a list by means of an array is inadequate in many aspects. There are the required static reservation of an unnecessarily extensive array, transfers of array items for the purpose of adding and removal, and the impossibility of further generalization. For these reasons, lists are typically represented as dynamic variables: linked lists. 16 Figure 2.1-3 Representation of a list by means of linking Linked list has the following properties: the control variables of the list contain a pointer referencing the first item of the list (H - head) the control variables of the list may also hold a pointer pointing to the last item of the list (T - tail) and a pointer referencing the current item of the list (C) the logical neighbours need not be physical neighbours since the memory representation is based on the dynamically allocated memory and free space or record management is used for disk representation in addition to the user data, each element of a list contains also a pointer referencing the next item on the list unless the item contains an additional pointer to another list item, the list is termed a single-directional list last item of a single-directional list may contain an empty pointer (with the nil value). However, if it contains a pointer referencing the first item of the list, the list becomes a single-directional cyclic list. each item of a list may also contain a pointer referencing the preceding list element: this makes the structure a double-linked list. when the last item of a double-linked list points to the first item and, at the same time, the first item points to the last one, the list is a cyclic double-linked one 17 2.2 Stack Objectives: The purpose of this article is to describe the stack data structure. Keywords: Stack; Stack The abstract concept of the stack is shown in the Fig. . Figure 2.2-1 Stack Semantic meaning A dynamic linear homogeneous data structure represented by a sequence of items. The items are entered in the stack in the same order as they arrive. The last item placed on stack is at the top of the stack. It is the only accesible item that can be retrieved. Stack is also described as LIFO (Last In First Out). Stack is used for temporary storage of data, where the last stored items are to be retrieved and processed first. Allowed operations: Stack initialization. Adding an item on the stack (PUSH) 18 Removal of an item from the stack Access to the top of the stack Testing whether the stack is empty Sometimes the access and removal operations are merged into a single one (POP) The stack is represented using: an array l inked variables Figure 2.2-2 Representation of a stack by means of an array Figure 2.2-3 Representation of a stack by means of linking Stack Representation Using an Array This technique is used in cases where the stack size is known to be smaller than certain value (or is known exactly). 19 Const Max = ... ; { An integer defining the maximum number of stack items} Type TP = ... ; { Type of items stored on stack } TZ = record ARR: array[1..Max] of TP; { Array of stored items } top:0..Max { Index of the top of stack item } end; // Stack initialization. Procedure INITS(var Z :TZ); Begin Z.Top := 0 end; // Adding an item on the stack. Procedure ADDS(var Z :TZ; P : TP); Begin with Z do if top = MAX then write ('Stack overfilled') else begin VRCHOL := Succ(top); ARR[top] := P end end; // Testing whether the stack is empty. Function EMPTYS(var Z : TZ) : Boolean; Begin EMPTYS:= Z.top = 0 end; // Removal of an item from the stack. Procedure REMOVES(var Z : TZ); Begin with Z do if EMPTY(Z) then write(' The stack is empty') else top := pred(top) end; // Accessing the top of stack item. Procedure ACCESSS(var Z : TZ; var P : TP); Begin with Z do if EMTPYS(Z) then write(' The stack is empty') else P := ARR(top) end; II) Stack Representation as Linked Dynamically Allocated Variables It is used when the number of items to be stored on stack is not known. As we work with the top of the stack only, we need just one pointer. However, an item must be added to contain a pointer to the previous item. Type TP = ... ; { Type of item. This may be a record } TPOINT = ^TElem; TElem = record Val : TP; Link : TElem end; 20 // Stack initialization. Procedure INITS(var Z : TElem); Begin Z := nil; end; // Adding an item on the stack. Procedure ADDS(var Z : TElem; P : TP); { Z points to the top of the stack } Var Pom : TElem; Begin New(Pom); { Location for a new item } Pom^.Val := P; { Saving the value } Pom^.link := Z; { Link to the previous item } Z := Pom { The new item is at the top of the stack} end; // Testing whether the stack is empty. Function EMPTYS(var Z : TZ) : Boolean; Begin EMPTYS:= Z = nil end; // Removing the item from the top of stack. Procedure REMOVES(var Z : TPOINT; var P : TP); { Z points to the top of the stack } Var Pom : TPOINT; Begin if EMPTYS(Z) then write(' The stack is empty') else begin P := Z^.Val; Pom := Z; Z := Z^.link; { Shifting the top of the stack } Dispose(Pom) { Disposing of the memory of the previous top of stack } end end; // Accessing the top of stack item. Procedure ACCESSS(var Z : TPOINT; var P : TP); Begin if EMPTYS(Z) then write(' The stack is empty') else P := Z^.Val end; 21 2.3 Queue Objectives: This article describes the queue data structure. Keywords: Queue; Queue The abstract concept of the queue is shown in the Fig. . Figure 2.3-1 Queue Semantic meaning Dynamic linear homogeneous data structure, which is used for temporary storage of information items to be processed in the order, in which they had been stored. It is characterized by the FIFO acronym, which stands for "First In First Out”. Allowed operations: queue initialization adding to queue (writing) removal from queue (reading) Queue representation by array by linked dynamic variables 22 Figure 2.3-2 Representation of a queue by means of an array Figure 2.3-3 Representation of a queue by means of linking Representation of a Queue as an Array A queue may be represented either as an array or as a linked list. When using the array representation, we must apply a static constraint to the array size (pointer referencing the last item or further). It is clear that while the queue is processed, its active part keeps shifting towards greater index values. This means almost certainly that the array will run out of its capacity at some point. This conflict may be resolved, for instance, by means of a cyclic buffer. A model of such buffer is shown in fig. , C ... pointer to the head of the queue, Z ... pointer to the end of the queue, I ... full/empty buffer indicator. 23 Figure 2.3-4 Cyclic buffer The structure of the queue operations should use circular array indices, i.e. after reaching the maximum value, it would start over again from the beginning. If sufficient array size is chosen for the maximum number of items to be placed in the queue, the preceding measure is adequate. The following definition can be used for queue representation and as a basis for its operations. Const Max : ... ; { Maximum possible queue length } Type TP : ... ; { Type of items placed in the queue } TF = record ARR : array[1 .. Max] of TP; { Array for items } rea: 1 .. Max; { Index of the item at the queue head } wri: 1 .. Max; { Index of the first empty place } ind: boolean { indication of full/empty queue } end; Queue Representation Using Linked Dynamic Variables If the queue length is unknown, it is advisable to use the tools of dynamic memory allocation for its representation. This eliminates the difficulties that arise from the array-based representation of queue. Essentially, such representation consists in a linked list with appropriate operations that make it function as the required queue. Type TP = ... ; UKAZ = ^TElem; TElem = record Val: TP; { Stored element value } link: TElem { Pointer referencing the next item in the queue. } end; TF = record first: TElem; { Pointer referencing the first item } last: TElem; { Pointer referencing the last item } number: Integer { Number of items in the queue } end; 24 It is possible to place items in the queue or remove them on the basis of other criteria, such as priority. (Such attributes are then added to the TElem record). Where items are to be enqueued or dequeued otherwise than at the queue end, i.e. for instance on the priority basis, representation as a double-linked list should be chosed as the best option. 25 3 Non-Linear Data Structures Objectives: The chapter is aimed at describing non-linear data structures. Keywords: Binary tree; General tree; Graph; Heap; Tree; 3.1 Graph Objectives: This article describes a graph as one of network data structures. Keywords: Graph; Graph Graphs are dynamic non-linear data structures capable of expressing relationships between elements. The elements are called vertices or nodes and the relationships are represented by the edges of the graph. Examples: Names of cities are graph nodes, roads are represented by edges. Substations are nodes, while high voltage electric lines are the graph edges. Each graph edge is related to two nodes. The edge connects these nodes. Where the pair of nodes connected with an edge is oriented (you may think of the roads between the cities as of one-way roads), the graph is oriented. Otherwise the graph is unoriented. Additional information can be attached to edges or nodes (e.g. number of inhabitants of a city - node, distance between cities along the edge). Such graphs are said to contain edge or node values. It is possible to represent graphs as either two-dimensional matrices or dynamic lists of nodes and edges. Matrix-Based Description of a Graph Where the maximum number of nodes is known (typical case), the operations on a graph may be in some cases converted into matrix operations. Graph is represented as an incidence matrix (two-dimensional array)) . This matrix expresses the incidence of (adjacent) nodes. It is simple to add or delete an edge and test for the existence of an edge. It is more difficult to work with nodes. Designing (analyzing) electrical networks is a typical example here. 26 Figure 3.1-1 Graph and its incidence matrix Where a graph is represented as an edge-node incidence matrix, the nodes are identified by row and column numbers and edges by matrix elements. If you follow a row of the matrix from left to right, the matrix elements indicate with boolean values the nodes, to which it is possible to traverse along the oriented edge from the given node. If you follow a column from top to bottom, you can find from which nodes it is possible to traverse to the node in question. For representation of a graph as a two-dimensional array, we introduce the following type declarations: Type TVert TGraph = 1 .. MaxV; { Maximum number of nodes } = array[TVrchol,TVrchol] of Boolean; In an oriented graph, adding and deletion are performed with the following operations: procedure ADDEDGE(var G : TGraph; V1,V2 : TVert); { Adds an edge from V1 to V2 } begin If not G[V1,V2] then G[V1,V2] := true else Write(' This edge exists already ') end; procedure REMEDGE(var G : TGraph; V1,V2 : TVert); { Removes the edge from V1 to V2 } begin If G[V1,V2] then G[V1,V2] := false else Write(' This edge does not exist ') end; An important term is the transitive closure of a graph . It is an incidence matrix, which describes the connectedness among all nodes regardless of complexity of the connecting path. 27 Figure 3.1-2 Graph and its transitive closure Program PGraph; {Transitive closure of a matrix-represented graph } Const MaxV = 6; Type TVert = 1 .. MaxV; { Maximum number of nodes; } TGraph = array[TVrchol,TVrchol] of Boolean; Var Graf: TGraph; Procedure TRANZIT(var PuvInc, TranzUzav : TGraph); Var I,J,K : 1 .. MaxV; Begin TranzUzav := PuvInc; for I := 1 to MaxV do for J := 1 to MaxV do if TranzUzav[J,I] then { If a path exists from J to I and } for K := 1 to MaxV do if TranzUzav[I,K] { if a path exists from I to K, } then TranzUzav[J,K] := true { then also the path from J to K exists } end; Procedure Reading(var MAT : TGraph); Var I,J : 1 .. MaxV; a:char; Begin for I := 1 to MaxV do for J := 1 to MaxV do begin write('Write the matrix value for [',I,',',J,']'); readln(a); 28 if a = '0' then MAT[I,J] := false else MAT[I,J] := true end; end; Procedure Writing(var MAT : TGraph; s:string); Var I,J : 1 .. MaxV; Begin Writeln; Writeln(s); for I := 1 to MaxV do begin for J := 1 to MaxV do if MAT[I,J] = false then write(' 0') else write(' 1'); writeln; end; end; begin Reading(Graf); Writing(Graf,'Original graph'); Tranzit(Graf,Graf); Writing(Graf,'Transitive closure'); end. Where the number of nodes changes during the graph processing, the matrix representation is not suitable. It is also inadequate when the incidence matrix is thinly populated. This means that the graph contains many nodes, which are rarely connected by edges. In such case, the representation with linked lists is appropriate. Implementation of Graphs Using Linked Lists One list shall exist for each node, containing as many items as the number of edges leaving or entering this node. In an oriented graph, the total number of items in the lists will equal the number of edges. In an unoriented graph, each edge will be present twice in the lists. With this type of representation, it is easy to add and remove edges and add nodes. It is more difficult to remove a node, since one has to remove those items from all lists, which represent the edges leaving or entering the node to be removed . Figure 3.1-3 Representation of a graph using linked lists 29 Example: A program for the transitive closure of a graph represented as a linked list. Program Graphs; {Transitive closure of a graph represented as list of edges } Const MaxV = '6'; Type TVert = '1'..MaxV; UHEdge = ^TEdge; TEdge = record vfrom: TVert; vto: TVert; next: UEdge; end; Tgraph = UEdge; Var Graph, Grapht: Tgraf; Procedure Add(p:UEdge; var O,K:TVert); Var pom: UEdge; Begin { Adds to the end of a non-empty list of edges } new(pom); pom^.vfrom := O; pom^.vto := K; pom^.next := nil; while p^.next <> nil do p := p^.next; p^.next := pom; end; Function Exist(p:UEdge; O,K:TVert):Boolean; Begin { Checks whether there is an edge from O to K } while (p^.next <> nil) and ((p^.vfrom <> O) or (p^.vto <> K)) do p := p^.next; if (p^.vfrom <> O) or (p^.kam <> K) then Exist := false else Exist := true; end; Procedure Copy(var G:UEdge; p:UEdge); Var pom: UEdge; Begin { Copies the list of edges to another } new(pom); G := pom; pom^ := p^; pom^.next := nil; while p^.next <> nil do begin p := p^.next; new(pom^.next); pom := pom^.next; pom^ := p^; pom^.next := nil; end; end; Procedure Reading(var Gr : TGraph); Var endp:char; pom,p: UEdge; Begin Gr := nil; writeln; repeat new(pom); repeat { Reads an edge and adds it to the end of list } 30 write('write from = '); readln(pom^.vfrom); until (pom^.vfrom >= '1') and (pom^.odkud <= MaxV); repeat write('write to= '); readln(pom^.vto); until (pom^.vto >= '1') and (pom^.vto <= MaxV); pom^.next := nil; if Gr = nil then gr := pom else begin p := Gr; while p^.next <> nil do p := p^.next; p^.dalsi := pom; end; write('Next = y/n'); readln(endp); until endp = 'n'; end; Procedure Writing(p : TGraf; s:string); Begin Writeln;Writeln(s); while p <> nil do begin write(' (',p^.next,',',p^.vto,') '); p := p^.next; end; end; Procedure TRANZIT(var PuvInc, TranzUzav : TGraph); Var I,J,K : TVert; Begin {Transitive closure } Copy(TranzUzav,PuvInc); for I := '1' to MaxV do for J := '1' to MaxV do if Exist(TranzUzav,J,I) then { If a path exists from J to I and } for K := '1' to MaxV do if Exist(TranzUzav,I,K) { if a path exists from I to K, } then Add(TranzUzav,J,K);{ then also the path from J to K exists } end; begin Reading(Graph); Writing(Graph,'Origina graph'); Tranzit(Graph,Grapht); Writing(Grapht,'Transitive closure'); end. 3.2 General Tree Objectives: This article describes general tree as one of network data structures. Keywords: General tree; General Tree A tree is an oriented graph, which contains no cycles and where no more than one edge enters each node. Due to the resemblance to family structure, the higher-level nodes are termed parents (ancestor) and the nodes derived from these are called children (descendants) . 31 Figure 3.2-1 General tree Root ... a node, into which no edge enters. Leaf ... a node, which no edge leaves. It is a custom to depict the trees upside down with roots at the top and leaves at the bottom. Trees have an important property, which consists in each node having the potential of becoming a root of another tree. Nodes may hold values. Since no more than one edge enters each node (only the root has no incoming edges), the edges need no values as their values may be represented by the node value. For representation, it is sufficient to describe the nodes. It is possible to view a general tree as a recursive sequence of mutually related single-level trees. Since the root of a single-level tree has many children and no more than one parent, we can consider only a single child and regard all others as its younger siblings. The sequence: parent - eldest child - younger child - youngest child - etc. is a simple linear list with its head represented by the parent and their children. . Figure 3.2-2 Representation of a general tree 32 Example: General tree declaration Type userinf uTree Tree = string[20]; { any type} =^Tree; = record rodic: uTree; ml_bratr: uTree; st_bratr: uTree; nejst_syn:uTree; obsah: userinf; end; It is possible to use general trees in genealogy: offspring family tree (the person's children) family tree (the person’s ancestors) in organizations organigram (structure of an organization) in biology: classification of organisms (kingdom, phylum, class, order, family, genus, species) or in engineering: bill of materials of a product (the decomposition of the product into assemblies, subassemblies, components and purchased items) where-used list (the use of a given component in various subassemblies, assemblies and products) 3.3 Binary Tree Objectives: This article describes binary tree as one of network data structures. Keywords: Binary tree; Binary Tree If each node of a tree has no more than two children, then the tree is a Binary Tree. Each node of a binary tree has therefore a left and, possibly, a right descendant. An ordered binary tree is a tree, in which the left descendants of each node have lower values than the root and the right descendants have higher values than the root. These trees are very important, being often used for representation of decision-making processes. Each node of a tree is represented by three items: value pointer to the left descendant pointer to the right descendant 33 Notes: The value may be even a complex structured object, such as a record. The whole tree is represented by a pointer referencing the root. The most convenient representation of a binary ordered tree is a dynamic linked list. Type TP = ...; { Type of values stored at nodes } TStrom = ^Vrchol; { The tree is represented by a reference to a node } Vrchol = record { Each node is a root of a sub-tree } Hodnota : TP; { Node value } Levy : TStrom; { Pointer to the left descendant } Levy : TStrom; { Pointer to the right descendant } Rodic : TStrom; { Pointer to the parent } end; { Creating a new node with the value P } Function NovyVrchol (P : TP) : TStrom; { The function returns a pointer to the newly created node } Var Pom : TStrom; Begin New(Pom); { Dynamic allocation of memory for a new node } With Pom^ do begin Hodnota := P; { Node value } Levy := nil; { The node has no descendants yet; it acts as a leaf } Pravy := nil; end; NovyVrchol := Pom end; We shall define a set of procedures for working with trees: Setting the pointer Levy of the S node to the SL node. Procedure SpojLevy (var S,SL : TStrom); Begin if S = nil then write(' The S node does not exist ') else S^.Levy := SL end; Setting the pointer Pravy of the S node to reference the SP node. Procedure SpojPravy (var S,SP : TStrom); Begin if S = nil then write(' The S node does not exist ') else S^.Pravy := SL end; Accessing the node value. Procedure VyberHodnotu (var S : TStrom,var P : TP); Begin if S = nil then write(' The S node does not exist ') else P := S^.Hodnota 34 end; Retrieving the pointer to the left descendant. Function VyberLevy (var S : TStrom) : Tstrom; Begin if S = nil then write(' The S node does not exist ') else VyberLevy := S^.Levy end; Retrieving the pointer to the right descendant. Function VyberPravy (var S : TStrom) : Tstrom; Begin if S = nil then write(' The S node does not exist ') else VyberLevy := S^.Pravy end; Creating an ordered binary tree. Procedure Vytvorstrom (var S : TStrom); { The input sequence of node values is 6,12,4,9,2 } Var X,Y : TP; Rodic,Act,Pom : TStrom; Begin Read(X); { Reads the node value } S := NovyVrchol; {Creates the node (X,nil,nil)} While not Eof do begin Read(X); { Reads the value of another node } Act := S; { Seeks an appropriate location within the current tree S} While not (Act = nil) do begin Rodic := Act; VyberHodnotu(Act,Y); { Stores the node value in Y } If (X < Y) { Deciding whether to continue } then { the search in the left or right } Act := VyberLevy(Act) { sub-tree } else Act := VyberPravy(Act) end; VyberHodnotu (Rodic,Y); { Upon finding a node with no descendants } If (X < Y) { (i.e. a leaf) decision is made whether to set } then { the new node as a left of right one } SpojLevy(Rodic,Pom) { descendant } else SpojPravy(Rodic,Pom) end end; The following tree will be generated . 35 Figure 3.3-1 Binary search tree It is possible to search a tree by traversing it in a number of ways. Let us consider an ordered binary tree. If we traverse the left subtree, print the node values and then traverse the right subtree, we will obtain an ordered (sorted) sequence of node values. For traversing trees, convenient recursive procedures are used. However, you must be careful, as in extensive tree structures you could run into problems with main memory or the size of stack used by your system. The traverse procedure: Procedure Prochazej(var S : TStrom); Var P : TP; Pom : TStrom; Begin If not ( S = nil ) then begin Pom := VyberLevy(S); { The left branches are traversed first } Prochazej(Pom) { Each node is a new tree. Therefore, the recursion is used } VyberHodnotu(S,P); { Upon traversing the branch to its end (nil)} Writeln(P); { the node value is retrieved and printed } Pom := VyberPravy(S);{ Then the right branch is traversed } Prochazej(Pom) end end; Upon ordering the displayed sequence of numbers: Procedure Serad; Var S : TStrom; Begin VytvorStrom(S); Prochazej(S) end; Binary trees are often used for storage, retrieval and sorting of information. To make the process efficient, the binary tree must be not only ordered but also balanced, i.e. with minimum number of node levels. Our tree is balanced. However, a different arrangement of its input values may, in an extreme case, result in that its search becomes in fact a sequential search. This is a degenerate binary tree . 36 Figure 3.3-2 Degenerate binary tree The height of an ideally balanced tree is less than log2 n. In the worst case, the height of a degenerate tree may be up to n where n is the number of nodes. The time of search for information in a balanced tree is T log2 n Balancing binary (and other) trees is a special and individual field of knowledge. Data on algorithmization of such processes can be found in literature. 3.4 Heap Objectives: Cílem článku je popis hromady jako jedné ze síťových datových struktur. Keywords: Heap; Heap Definition Heap is a binary tree whose nodes hold integer values. Heap has the following properties: Each node has two descendants, except for those in the last or the second to last levels. The second to last level contains, from left to right, nodes with two descendants, then no more than one node with a single descendant and then nodes with no descendants. Values are assigned in such fashion that the value of any node is no higher than the value of any 37 descendant. Fig. shows an example of a heap. Figure 3.4-1 Heap The result of this arrangement is that the top of the heap always contains the item with the smallest value. Operations on the Heap Two operations are defined on the heap: 1) Insert (Value) - Inserts a new node The location of the new node results unambiguously from the heap definition. Values of the nodes must be checked and, if needed, the nodes shall be exchanged to ensure the compliance of values with the definition. If we apply the Insert (7) operation on the previous heap, the heap will look like the figure . Figure 3.4-2 Heap upon inserting a new item 2) Extract_min - Removing the item with the lowest value. The lowest value item is at the top of the heap. The place of the removed top item will be taken by the last inserted node (which is unambiguously identified) and the heap items will be rearranged to meet the heap rules. If we apply the Extract_min operation on the previous heap, the heap will look like the figure 38 . Figure 3.4-3 Heap upon removal of the lowest value item Heap Representation. Advantages of representing a tree as heap include the fact that its items may be stored as vectors (onedimensional arrays). Figure 3.4-4 Representation of a heap The left descendant of the vi item is at the 2*i position The right descendant of the vi item is at the 2*i+1 position. The heap is used for sorting. Such method is neither stable nor natural. The sorting time is as follows: T n . log2 n 39 4 Tables Objectives: The chapter is aimed at describing tables as data structures. Keywords: Table; 4.1 Tables and Their Key Items Objectives: This article explains the term “table”. Keywords: Table; Tables and Their Key Items Tables are dynamic linear homogeneous data structures related to storage of data in the computer’s main memory. Where data is stored mainly on disk, we use the term “typed files”. A number of algorithms may be used both with tables and with typed files. At the same time, one must be aware of the considerable difference between the main memory and hard disk data processing speeds. Figure 4.1-1 Table It is possible to view tables as one-dimensional arrays of record variables. (In other words, they are homogeneous linear structures of items, where the items themselves may be heterogeneous.) Items of such array are called table items. Processing of tables is based on keys, which are part of table items. Each table item consists of two parts: 40 key user data There might be multiple keys in the table. These are classified as primary and secondary keys. The primary key should be unique within the table and should identify the table item unambiguously. On the contrary, secondary keys are typically not unique, as one value of the secondary key may be found in several items. Basic operations on a table include: Initialization (creation of an empty table) Insertion of a new item Searching for an item based on the primary key Searching for the first item based on the secondary key Searching for the next item based on the secondary key Modification (rewriting) the sought item Cancelling an item Tables may be divided into simple ones, where the keys are included in the table and into index tables, where the keys are listed in various separate index tables. Some keys may be listed in the basic table only, while others in separate tables. The following fundamental table types may be defined according to the procedures of insertion, searching and cancellation of items: input-sequence table ordered table hash table Index tables may be either of the same types or created by special techniques (e.g. tree structures). 4.2 Input-Sequence Table Objectives: This article is intended to demonstrate processing of a non-ordered table. Keywords: Input-Sequence Table; Input-Sequence Table The input-sequence table represents the simplest type of table. Its items are not organized according to a key. Instead, they are recorded in the order of their arrivals. The benefits of input-sequence tables lie in their simplicity. They are used wherever large numbers of items are processed in mostly sequential fashion. Such tables can be represented as arrays of sufficient sizes. The items of such arrays are records consisting of: indicators showing whether the table item is valid or whether it has been deleted key 41 user data The purpose of the item validity indicator is to make item cancellation faster. Then, if items are being cancelled, the next items need not be moved. Marking the item as cancelled is sufficient. Items are physically removed upon reorganizing the table. Reorganization can be performed at times of low computational loads or upon reaching certain table occupation level. It is advisable to define a table control structure, which consists of three elements: maximum number of items in the table (number of array items) actual number of items in the table an index of the last item Table Initialization To initialize a table means to define the maximum number of table items and set the remaining elements of the two control structure to zero. Insertion in Table Insertion of a new item includes a check whether the index of the last item in table is equal to the maximum number of items. If so, and the actual number of items is lower than maximum, reorganization of table is performed and the empty items are eliminated. When the index of the last item is lower than the maximum number of items, the new item is inserted after the last one, its indicator is set to “valid” and the actual number of items and the index of the last item are raised by 1. Table Searching Finding an item according to a specified key is a sequential operation. Starting with the first item, the specified key must be compared with the values of keys in the table, while skipping the items marked as cancelled. If a match is found, the item can be retrieved. If the last item is reached without finding a matching key, the searched item is not present in the table. The average search time in the inputsequence table is proportional to N/2 if the item is present in the table or proportional to N if the item is not present, where N is the index of the last item in table. Modifying a Table Item This operation involves finding the item according to the specified key and changing the stored data. The control structure of the table remains unchanged. Cancelling a Table Item Cancellation of an item consists in finding the item according to the specified key, setting the indicator to cancelled and decreasing the number of actually present items by one. Table Reorganization Upon reorganization, the index of the last item in table equals the actual number of items in table. Fig. shows an example of an input-sequence table. 42 Figure 4.2-1 Input-sequence table Algorithm for Searching an Input-Sequence Table The algorithm for finding an item in a table is demonstrated with an example of finding a record in a typed file. The search time is proportional to the number of records in the file. unit definice; // Author: Kopecek Date: 3rd Oct, 2006 // Purpose: sequential search - definition interface const NAME_LEN = 25; type t_jmeno = array[1..NAME_LEN] of char; t_jmena = record jmeno: t_jmeno; filler:array[0..2] of char; end; t_soubor = file of t_jmena; implementation end. Search Algorithm 43 unit sekvencni_f; // Author: Kopecek Date: 3rd Oct, 2006 // Purpose: sequential search - algorithm // // Subprograms: // rovno ... compares two strings to find if they are equal // sekvencni ... actual algorithm interface uses definice; function sekvencni(var f:t_soubor;s:t_jmeno): integer; implementation function rovno(a,b:t_jmeno):boolean; var i:integer; begin rovno := true; for i := 1 to NAME_LEN do if a[i] <> b[i] then rovno := false; end; function sekvencni(var f:t_soubor;s:t_jmeno): integer; // Algorithm: // the record pointer is set to -1 // the search flag is set to not found // until end of file is reached or the item found // perform the following: // - set the pointer to next record // - read the next record // - if the currently retrieved record is the required one, the flag // shall be set to found // // the result is either the number of the record found or -1 var nalezeno :boolean; f_jmeno :t_jmena; zaznam :integer; begin nalezeno := false; zaznam := -1; reset(f); while not eof(f) and not nalezeno do begin inc(zaznam); read(f,f_jmeno); if rovno(f_jmeno.jmeno,s) then begin nalezeno := true; end end; if not nalezeno then sekvencni := -1 else sekvencni := zaznam; end; 44 end. Main Program program sekvencni_p; // Author: Kopecek Date: 3rd Oct, 2006 // Purpose: sequential search - main program // // Parameters: no parameters, the data will be read from the ordered file jmena.txt // // Note: The program only runs correctly when the names used contain // - only lower case letters // - only upper case letters // - only digits uses SysUtils, definice in 'definice.pas', sekvencni_f in 'sekvencni_f.pas'; var f:t_soubor; jmeno:t_jmeno; s:string[NAME_LEN]; i,sek:integer; begin assign(f,'jmena.txt'); repeat writeln('enter name or ".":'); readln(s); for i := 1 to NAME_LEN do jmeno[i] := ' '; for i := 1 to length(s) do jmeno[i] := s[i]; sek := sekvencni(f,jmeno); // returns -1 when not successful, otherwise returns the record number if sek >= 0 then writeln('the specified name ',jmeno,' is in the no. ',sek,' record') else writeln('the specified name ',jmeno,' is not in the list'); until s = '.'; close(f); end. Test Data alena jirina alfons danuse hugo john zuzana zita judita jana jaromir cecilka franta karel * * * * * * * * * * * * * * 45 ludek eric dalimil rudolf patrik * * * * * Program Results enter name or the specified enter name or the specified enter name or the specified enter name or the specified enter name or the specified ".":eric name eric ".":john name john ".":alena name alena ".":xxxxxxxx name xxxxxxxx ".": name . is in the no. 15. record is in the no. 5. record is in the no. 0. record 4.3 Ordered Table Objectives: The purpose of this article is to demonstrate the work with a table ordered according to a key. Keywords: Ordered Table; Ordered Table The ordered table represents another data structure type. Its items are stored in the ascending order of the key values. Item cancellation consists in marking the item as cancelled. Difficulties arise from insertion. For each item to be inserted, a suitable position is needed. If there is no empty position (cancelled item), it should be created by shifting the remaining items of the table by one position. This would greatly reduce the insertion speed. This is why the table is divided into an ordered and an nonordered parts. Reorganization involves ordering of the non-ordered part of table. The items of this part are then placed into the ordered part of table. Such tables can be represented as sufficiently large arrays. The items of such arrays are records consisting of: indicator showing whether the table item is valid or whether it has been cancelled key user data The control structure of the table consists of four elements: maximum number of items in table (number of array items) the actual number of items in table the index of the last item of the ordered part of table the index of the last item of the non-ordered part of table Table Initialization 46 To initialize a table means to define the maximum number of items of table and set the remaining three control structure elements to zero. Insertion in Table Inserting a new item includes a check whether the index of the last item in the non-ordered part of table is different from the maximum number of items. If so, and the actual number of items is lower than the maximum, at least the reorganization of table must be performed and the empty items eliminated. When the last item index in the non-ordered part of table is lower than the maximum number of items, the new item is inserted after the last one, its indicator is set to valid and the actual number of items and the index of the last item are raised by 1. Finding an Item Finding an item with a specified key value involves binary search in the ordered part of table and sequential search in the non-ordered part of table. The binary search means that certain limits are defined: first and last item of the ordered part of table. Then the program retrieves the item in the middle of the range between the limits and compares its key with the specified value. If there is a match between them, the search ends. Otherwise, the search continues: if the specified key was lower than that of the item in the middle between the limits, the upper limit is reset to the index value of the middle item minus one. If the specified key was higher than the middle one, the upper limit shall be reset to the index of the middle item plus one. Then the item in the middle between the reset limits shall be retrieved. The program repeats this procedure until the specified item is found or the upper limit becomes smaller than the lower one. In the non-ordered part of the table, the search is sequential. The average search time in the ordered part of table is proportional to log 2 N, where N is the index of the last item of the non-ordered part. This means that the algorithm is very fast. It is desirable to reduce the length of the non-ordered part of table, as its search time is directly proportional to its number of items. Modifying an Item This operation involves finding the item according to the key and changing the stored data. The control structure of the table remains unchanged. Cancelling an item Cancelling an item consists of finding the item with the specified key value, setting the indicator to cancelled and decreasing the actual number of items by one. Table Reorganization Upon reorganization, the index of the last item in the ordered part of table equals the actual number of items in table. The non-ordered part of table may either be placed after the ordered part or located at the end of table. Ordered tables are used when specified items need to be found quickly and when the type of processing based on moving to next item in an ascending order is required. The following figure shows an example of an ordered table. 47 Figure 4.3-1 Ordered table Algorithm for Searching an Ordered Table The algorithm consists of two blocks: searching the ordered part of table if the item was not found, then: searching the non-ordered part of table The searching of the non-ordered part of table was demonstrated in the previous article. The searching of the ordered part of table will be demonstrated with the search in a typed file ordered according to key values. unit definice; // Author: Kopecek Date: 30th Oct, 2003 // Purpose: binary search - definition interface const NAME_LEN = 25; type t_jmeno = array[1..NAME_LEN] of char; t_jmena = record jmeno: t_jmeno; filler:array[0..2] of char; end; t_soubor = file of t_jmena; 48 implementation end. Search Algorithm unit puleni_f; // Author: Kopecek Date: 30th Oct, 2003 // Purpose: binary search - search algorithm // // Subprograms: // rovno ... compares two strings to find if they are equal // mensi ... compares two strings using the less than sign // puleni... the algorithm itself interface uses definice; function puleni(var f:t_soubor;s:t_jmeno): integer; implementation function rovno(a,b:t_jmeno):boolean; var i:integer; begin rovno := true; for i := 1 to NAME_LEN do if a[i] <> b[i] then rovno := false; end; function mensi(a,b:t_jmeno):boolean; var i:integer; bool:boolean; begin bool := false; i:= 1; while (i <= NAME_LEN) and // no more than the whole string length not bool and // once the ordinal value of one character is lower not (a[i] > b[i])do begin // or higher, the operation terminates if a[i] < b[i] then bool := true; inc(i) end; mensi := bool; end; function puleni(var f:t_soubor;s:t_jmeno): integer; // Algorithm: // the lower limit of the search shall be set to the beginning of file - 0 record // the upper search limit is set to the last record / filesize(f) - 1 // the search flag is set to “not found” // while the lower limit is smaller than the upper one and nothing has been found, // the following is performed: // - the middle of the range is determined as the average of the upper and lower search limits // - the program reads the record in the middle of the range // - if the currently retrieved record is the required one, the search flag // shall be set to found 49 // - if the currently retrieved record is smaller than the required one, the lower // search limit will be set to a value that is greater by 1 than the number of the retrieved record // - if the currently retrieved record is larger than the required one, the upper // the search limit will be set to a value that is lower by 1 than the number of the retrieved record // the result is either the number of the record found or -1 var dolni,horni,stred:integer; nalezeno :boolean; f_jmeno :t_jmena; begin dolni := 0; stred := -1; horni := filesize(f)-1; nalezeno := false; while not (dolni > horni) and not nalezeno do begin stred := (dolni + horni) div 2; seek(f,stred); read(f,f_jmeno); if rovno(f_jmeno.jmeno,s) then begin nalezeno := true; end else if mensi(f_jmeno.jmeno,s) then begin dolni := stred +1; end else begin horni := stred -1; end; end; if not nalezeno then puleni := -1 else puleni := stred; end; end. Main Program program puleni_p; // Author: Kopecek Date: 30th Oct, 2003 // Purpose: binary search - main program // // Parameters: no parameters, as the data will be read from the ordered file jmena.sor // // Note: The program only runs correctly when the names used contain // - only lower case letters // - only upper case letters // - only digits uses SysUtils, definice in 'definice.pas', puleni_f in 'puleni_f.pas'; var f:t_soubor; 50 jmeno:t_jmeno; s:string[NAME_LEN]; i,pul:integer; begin assign(f,'jmena.sor'); reset(f); repeat writeln('enter name or ".":'); readln(s); for i := 1 to NAME_LEN do jmeno[i] := ' '; for i := 1 to length(s) do jmeno[i] := s[i]; pul := puleni(f,jmeno); // returns -1 when not successful, otherwise returns the record number if pul >= 0 then writeln('the specified name ',jmeno,' is in the no. ',pul,' record') else writeln('the specified name ',jmeno,' is not in the file'); until s = '.'; close(f); end. Test Data alena alfons cecilka dalimil danuse eric franta hugo jana jaromir jirina john judita karel ludek patrik rudolf zita zuzana * * * * * * * * * * * * * * * * * * * Program Results enter name or the specified enter name or the specified enter name or the specified enter name or the specified enter name or the specified „.“:alena name alena „.“:john name john „.“:zuzana name zuzana „.“:xxxxxx name xxxxxx „.“:. name . is in the no. 0. record is in the no. 11. record is in the no. 18. record is not in the file is not in the file 4.4 Hash Table 51 Objectives: The purpose of this article is to demonstrate how to work with a table, in which information is located according to key values. Keywords: Hash Table; Hash Table This is another approach to arranging a table: calculating the address of the table location using the value of the key: A = F(K,N) A - address of the location in the table K - value of the key N - number of items in the table The F function is called a transformation function . The problem consists in finding the F function. The properties of the key can be used for this purpose. Simple Transformation Function The simplest transformation function is a linear function, where the key is a natural number ranging from B to B+N and B is an arbitrary natural number. For instance, this may be implemented for store receipt cards numbered in a continuous ascending order. Another simple algorithm can be used for computing an address of a storage location in a warehouse. Lanes between racks (R) are marked as ´A´-´F´, the distance (D) ranges between 1-50, and height (V) between 1-10. The F function can be written as: A = (ord(R) - ord(´A´)) * 500 + (V-1)*50 + D General Transformation Function - Hashing In general, it is not always possible to rely on the properties of the key. You can think of the key as of a value between 1 - 256L, where L is the byte length of the key. The F function maps this value on a range matching the table size. There is another requirement, too: the distribution of data within the table should be as uniform as possible, regardless of any clusters of the key values. Giving an example of a function, which meets such requirements: a function that calculates the address in the table by dividing the value of the key by the table length and using the division remainder. The optimum distribution of addresses can be achieved if the number of table items is a prime number. Otherwise, clustering occurs with periods equal to the prime factors of the number of items of table. The function that converts the value of the key into an address is called hash function. Figure 4.4-1 Transformation function 52 Synonyms However, it is possible that different keys will be assigned the same address. Keys that were assigned the same address are called synonyms. Hash Table Representation The table can be represented as a sufficiently large array. Since the synonyms might occur, the suggested maximum utilization of the table capacity is 60 to 70%. Items of the array representing a hash table are records consisting of: an indicator showing whether the table item is valid or whether it has been cancelled two indices for resolving the synonym occurrence (OA, OB) key user data The control structure of the table consists of four elements: the maximum number of items in table (number of array items) the actual number of items in table Resolving Synonym Conflicts The occurrence of synonyms is resolved in the following fashion: when the program attempts to insert an item, calculates its address and obtains an address, which is already occupied and, at the same time, the OA index equals zero, the program places the item into the nearest empty location in the table and sets the OA index to this actual address. when the program attempts to insert an item, calculates its potential address and obtains a value, which is already taken and, at the same time, the OA index differs from zero, the program places the item to the nearest empty location in the table and tests the item, to which the OA index points. If the OB index of this location is zero, the program sets it to the actual address. If not, the program continues checking the OB index until it finds one with a zero value and sets it to the actual address. Statistics prove that unless the number of items present in the table exceeds 60-70% of the table capacity, the average number of accesses using the OA and OB indices will be less than 1.3. Table Initialization Initialization of a table includes defining the maximum number of items, setting the actual number of items in table to zero, marking all items in table as cancelled and setting the OA and OB indices to zero. Item Insertion When inserting a new item, the program checks whether there is available space in the table. If so, the program calculates the address, resolves the possible synonym conflicts and raise the number of items by 1. Finding an Item Finding an item according to a specified key is based on calculating the address. If this address contains neither a valid item nor a key matching the specified one, then the OA and OB indices are used. The average frequency of access is less than 1.3 regardless of the table size and the number of its occupied locations. 53 Modification of an Item This operation involves finding the item according to the key and changing the stored data. The control structure of the table remains unchanged. Cancellation of an Item Cancellation of an item consists of finding the item according to the key, setting the indicator to “cancelled”, modification of OA and OB indices while leaving items in their locations, and decreasing the number of actually present items by one. Reorganization Reorganization is not needed. However, the consequence of this is the impossibility to find neither the next nor the preceding item based on the alphabetical order. Application of Hash Tables Hash tables are used when specified items need to be found quickly and when the processing based on finding the next item in an ascending order is not necessary. Figure 4.4-2 Hash table An example of a hash table is shown in figure . The address generated for DANA is the same as that of ALENA. The next empty location will be used (10) and the OA index of the item (9) will be set to 10. The CYRIL and PAVEL synonyms will be resolved in the same manner. The ROBERT, LUDEK and ROSTISLAV synonyms all generate the address 6. In this case, the OA index of the ROBERT item (6) and 54 the OB index of the LUDEK item (7) will be used. If another key generates the address 7, the OA value of this address will be used. 4.5 Tables with Multiple Keys Objectives: The purpose of this article is to demonstrate how to work with a table with multiple keys. Tables with Multiple Keys Where the amount of user data is extensive or the table contains multiple keys, it is advisable to build a master table for each of the tables to contain a single key and item number of the basic tables. These master tables are called index tables. Index tables can be organized in different ways (as input-sequence tables, ordered or hash tables). There may be multiple occurrences of identical keys. Insertion, cancellation and modification of keys in the basic table must involve modifications to the items of the index tables. A key must be specified for each search. The program selects the appropriate index table according to the key, finds its match and the pertinent item in the basic table. Figure 4.5-1 Table with multiple keys Spreadsheets and databases are tailored to working with tables. They offer powerful tools not only for 55 processing of individual table items but also for groups of items and table columns. With them it is also possible to automatically fill in table fields on the basis of other fields, insert subtotals and many other statistical functions. 56 5 Products and Orders Objectives: This chapter gives a simplified overview of the types of data used to describe products and their manufactured and purchased parts. Such data serves for time-planning of the production and for planning the amounts and requirements for workstation capacities. 5.1 Selected Data Structures Used in Industrial Engineering Objectives: This article gives introduction to product description, manufacturing and planning. Keywords: Bill of Materials; Customer order; Item; Manufactured item; Purchased item; Technological routing; Selected Data Structures Used in Industrial Engineering In order to describe a product and to plan and monitor its manufacturing, we need data from the production preparation process conducted by the design and technology departments. This course only deals with the essential data and functions required for the IS/IT operations of an engineering plant. For instance, the number of lines of the demonstration program (about 1,000) covering the functions of the bills of material and the production routing is a mere fraction of the number of lines of an actual production control software (about 4,000,000). Essential data structures and operations performed on them in the field of engineering include the following: Items (purchased parts and materials, manufactured parts, sub-assemblies, assemblies, products) Bill of materials and its items and relations Technological routing, operation, workstation Print-outs of exploded bills of materials (BOM), the BOM time-planning and specified amounts Time-planning of the technological routing Calculation of the cost-based price of the product Order, order entries and its time-planning and quantity planning 57 Figure 5.1-1 Selected structures 5.2 Manufactured and Purchased Items Objectives: This article demonstrates data structures for description of manufactured and purchased items. Keywords: Item; Manufactured item; Purchased item; Manufactured and Purchased Items Items include purchased parts and materials, manufactured parts, sub-assemblies, assemblies and products. Each manufactured item is described with a bill of materials, which is the list of the items of the next lower level required for production of the item in question. These may consist of either materials (steel bars or sheet) or purchased semi-products (e.g. castings or forgings). An assembly is characterized by a list of manufactured parts, sub-assemblies, joining parts and paint, for instance. Data Fields of an Item Since the word "item" may have both the meaning of manufactured or purchased parts and the meaning of data items, we will use the term “data field” consistently in the following text. Moreover, the term data field is common in mass data processing. The minimum data fields required for describing the essential functions include: 58 item name (entered by user) - a unique identification, which typically includes a sequential number from the list of purchased items and the manufactured item drawing number required amount (entered by the user) planned amount (calculated) costing amount - (costing amount) used for calculating the costs and lead times in situations, when the required and planned amounts were neither entered nor calculated and the factory price and duration of production estimates are needed lead time (for obtaining or producing an item) (it is either user-defined or calculated if operations had been entered for the item) total lead time (calculated) - the sum of maximum durations of individual assembly stages low level code (calculated) - the maximum assembly level, where the given part is used. This term is important for algorithmization. It will be clarified later on. item price (for purchased items this information is entered by user, while for manufactured items it is either entered by user or calculated, depending on whether their production routing is available. price based on routing (calculated) Furthermore, the properties of an item may include units of measurement (for stock, purchasing, sales, prices), material standards, sorting codes, names and text descriptions of items, supplier, date of creation and change, names of employees in charge, amounts in store and in production. In fact, items may have tens to hundreds data fields assigned. Items may be classified into those neutral in relation to orders, i.e. those items that do not depend on an order and into those dependent on orders. Further, we will only consider the order-independent items. Figure 5.2-1 Bicycle items 59 Figure shows selected purchased and manufactured items for bicycle assembly. For simplicity, the frame is listed as a purchased item although it is manufactured from pipes. 5.3 Bill of Materials Objectives: This chapter describes the bill of materials as a data structure. Keywords: Bill of Materials; Item; Bill of Materials Definition of a Bill of Materials Bill of materials represents the structure of a product. From the data processing viewpoint, the bill of materials is an acyclic oriented network data structure. Nodes contain the purchased parts and materials, manufactured parts, sub-assemblies and assemblies of a product. The edges represent links between the higher-level and lower-level items, listing the number of the latter required for production of the former. A purchased item is represented by a node, in which an oriented edge terminates and where no edge starts. Final products are the top items of the bill of materials. These are the nodes, where oriented edges start and no edges enter. Edges are represented by BOM links. BOM Links The minimum data fields required for describing the essential functions include: name of the higher-level item (entered by the user) name of the lower-level item (entered by the user) number of lower-level items for the higher-level unit (entered by the user) - pieces are typically used as units for manufactured items.. Depending on the unit of measurement selected, the quantity may be shown as a decimal number. BOM Explosion Exploding the bill of materials produces the list of items that are required for production of the higher-level item: single-level exploded list contains only those items used directly in the higher-level item multi-level exploded list contains the items used directly in the higher-level item, the items used in lower-level items and exploded lists of these down to the purchased items where-used exploded list contains the items, where the current item is used multi-level where-used exploded list contains the items and higher-level sub-assemblies, assemblies and products where the current item is used summarized bill of materials lists the total numbers of individual items (typically purchased ones) regardless of their position, which are required for manufacturing the item in question (typically the top item) The exploded bill of materials is not a permanent data structure. It is a product of the program, which processes the bill of materials links. 60 The exploded list contains multiples of required numbers of items on individual levels (required for production). Bill of Materials Example Figure shows an example of structure of a bill of materials for three products: A, B and C. H, I, J and F are purchased items. Arrows represent links. The figure explains the concept of the low level code. When A, B and C are top products on the zero level, then D, E, F and G are first level items and H, I and J are second level items. The J item enters both 1 and 0 levels. The low level codes will be changed by, for instance, incorporating the A product into some higher-level assembly X (e.g. a turbine in a power plant). Figure 5.3-1 Structure of a bill of materials Figure shows an example of a simplified bill of materials of a bicycle. 61 Figure 5.3-2 Bill of materials of a bicycle 5.4 Technological Routing, Operation, Workstation Objectives: The purpose of this chapter is to give a description of the following data structures: technological routing, operation and workstation. Keywords: Item; Operation; Technological routing; Workstation; Technological Routing, Operation, Workstation Workstation In order to define a technological routing, the workstation must be determined, where the actual operations of the technological routing are performed. Workstation is a set of means of work specified in terms of the technology, capacity and occupied space. From the viewpoint of the production process control, it is a comparatively independent and further indivisible element of the production system. 62 Considering the basic data model, the following data fields are required: workstation number (entered by the user) rate - CZK/hr (entered by the user) transition time (entered by the user) Workstation number may identify a particular machine, sub-assembly or a group of machines, which must be differentiated for the purpose of production scheduling and control. Transition time is the time, which must be added to the technological process time of an operation for time-planning purposes: it is the sum of the transfer time and planned time offset (work in progress). Generally, one can consider a two-dimensional model of transition times between possible combinations of successive workstations on the routing. In a simplified view, it is possible to assign the transition time to one workstation only. The underlying assumption is that part of this time is used before the start of the operation and the rest is used up upon its end. A more specific breakdown is generated on the shop-floor control level. Routing The technological routing is a sequence of operations required for production of the part. It is possible to consider various production routings for each manufactured part. Differences between such routings will consist, for instance, in minimum and maximum numbers of products for economically optimal production (universal, unit, and series production). Each of the routings will consist of the following data fields: number of the manufactured item (entered by the user) index of the routing (entered by the user) minimum number of products for economically optimal production (entered by the user) maximum number of products for economically optimal production (entered by the user) The item number and the routing index are unique identifications of each routing. Operation The operations are numbered (as routing items) and maintaining their order in production is mandatory. There may be multiple occurrences of a workstation throughout the routing. Substantial data for identification of an operation includes the item number, the routing index and the operation number. Each operation has these data fields: name of the item (entered by the user) index of the routing (entered by the user) sequential number of the operation (entered by the user) workstation number (entered by the user) preparation time (entered by the user) unit time (entered by the user) 63 Figure 5.4-1 Sample routing 5.5 Data Model Objectives: The purpose of this chapter is to give a description of the following data models: bill of materials, operation and workstation. Keywords: Data model; Data Model The data model is based on the concept of a single-level bill of materials and operations 64 . Figure 5.5-1 Single-level bill of materials The following integrity constraints hold: a higher-level item may consist of various lower-level items a lower-level item may be used in various higher-level items a technological routing comprises a number of operations each operation is assigned one workstation a number of operations can be performed in one workstation a single workstation may be used multiple times in a single routing the order of operations is important with regard to the routing It is possible to assign texts of different lengths to items and operations. This is implemented by using variable numbers of rows of fixed lengths. It is possible to construct a model of basic data of engineering production based on these conditions 65 : Figure 5.5-2 Basic data model 5.6 Working with the Bill of Materials Objectives: The purpose of this chapter is to demonstrate algorithms for working with the bill of materials. Keywords: Bill of Materials; Working with the Bill of Materials Processing the Bill of Materials Processing a bill of materials is rather complex in terms of algorithm. There is a simple demonstration program with about 1,000 lines of code, which has been created for study purposes. The following algorithms have been tested using this program. Circular Reference Check for Insertion of Links in the Bill of Materials Billl of materials is defined as an acyclic network structure. It would be illegal for a parent item to be a direct or indirect descendant of its direct or indirect child. An example of such circular reference is bill of materials of a locomotive wrongly listing the whole locomotive as a component part of its frame. 66 In real-world production control systems it is necessary to ensure that: no circular reference occurs if circular reference occurs, possibly through data error or a failure of some part of program, no infinite cycle or recursion start during processing. This is a very complex issue leaving great responsibility with the programmer. Algorithm: 1 The underlying assumption is that it is possible to create the bill of materials in steps and modify it by inserting more links. 2 An empty bill of materials (with no links) contains no circular references. 3 Prior to inserting a new link, the full exploded bill of materials of the new child item must be searched to verify that it does not contain the new parent item. 4 Furthermore, prior to inserting a new link, the full exploded where-used list of the new parent item must be searched to verify that it does not contain the new child item. Points 3 and 4 are typically resolved by recursion or by appropriate conversion of recursion to a cycle. Printing Exploded Bill of Materials Printing an exploded bill of materials or a where-used list, is a typical recursion task. Algorithm: For the processed node (e.g. the top-level item), the print command for the bill of materials is called with the parameter for the total amount = 1. Printing data for one level consists in sequential printing of its next lower-level items including their quantities required and the total quantity for the performance as the number of lower-level items required for the higher-level item multiplied by the parameter of the print command. Printing a link is followed by a recursive call of a print command with a lower-level item as the initial node and with entered number required for the lower-level item in question. When there are no lower-level items left, the recursion ends. Each printed recursive level is indented (proportionately to the bill of materials level; not the low level code). In this fashion, the printed bill of materials is oriented from left to right. Time-Planning of the Bill of Materials Let us have a bill of materials as shown in figure . 67 Figure 5.6-1 Time-planning of bill of materials 68 The purpose of time-planning is to find the total lead times. Algorithm The algorithm consists of two steps: calculation of the low level code calculation of lead times a) calculation of the low level code setting all levels to zero leaving the values of all levels, which have no higher-level items assigned, at zero setting the next lower level to 1 on level 1 and the following, level values of all exploded items shall be set to the maximum from the current level and ordinary level increased by 1 b) calculation of lead times the total lead time for the lowest level shall be set to the amount of lead time the total lead time of a higher level item shall be set to the greater value from the previously defined lead time and the sum of the lead time of the higher-level item and the total lead time of the lower-level item unless level 1 is reached, the process is repeated starting at point 2 Defining Amounts in the Bill of Materials Figure shows the same bill of materials as that used for explanation of time-planning. Figure 5.6-2 Calculation of amounts The purpose is to calculate the required numbers of items regardless of the production time and the position of the item in the exploded bill of materials. We assume to have the low level code value calculated at the time-planning stage. 69 Algorithm: 1 2 3 setting the planned quantities of pieces to zero setting the level to 0 on the specified level: adding the current required amount to the planned amount. For the next lower level: adding the numbers of the explosion list to the planned number if there is a lower level, then moving to another level and continuing at point 3 70 5.7 Working with the Technological Routing Objectives: Cílem kapitoly je ukázat algoritmy pro práci s technologickým postupem. Keywords: Technological routing; Working with the Technological Routing Operations Time-Planning The purpose of operations time-planning assembly based on the routing. is to find the lead time of component production or of an Algorithm: For all items with prescribed routings, the calculation shall be as follows: if the planned amount had been already calculated, the duration of the operation shall be the sum of the preparation time, the time of transit (from the workstation) plus the unit time multiplied the by the planned amount if the planned amount had not been calculated yet, the costing amount shall be used the lead time for production of a part or for assembly is the sum of individual operation times The lead time for items with no routings does not change (its estimate can be entered manually). Figure 5.7-1 Time-planning of operations 71 Determination of Component Price Based on the Routing Price can be calculated using the routing. Algorithm: For all items, which have their routings, the calculation for each particular operation shall be as follows: if the planned amount has already been calculated, the price = (preparation time + unit time * the planned amount) * rate (for workstation) when the planned amount has not been calculated yet, the costing amount shall be used The price of items with no routings and zero costing and planned quantities does not change. Figure 5.7-2 Determination of operations' prices Calculation of the Cost-Based Price of the Product The purpose of this calculation is to find the prices of individual items. The price is calculated according to BOM upon the prices of individual component parts and assemblies have been determined on the basis of the routing. Algorithm: 1 2 3 setting the level to the maximum value (lowest) for all items on this level: if non-zero price is calculated using the technological routing, it shall be added to the prices of all items of the lower lever making up this item. Otherwise the price is kept. move to higher level and continue with point 2 (if there is a higher level - the process is completed on level 0) 72 Figure 5.7-3 Product price 5.8 Order, Order Entries Objectives: The purpose of this chapter is to show how to describe a customer order and how an order is linked to items, bill of materials and the routing. Keywords: Item; Order; Order, Order Entries An order consists of a heading and entries. Order Heading An order heading may contain the following data fields: order number (entered by the user) - unique identification name of customer (entered by the user) due dates (entered by the user) Order Entries Order entries may contain the following data fields: order number (entered by the user) entry number (entered by the user) item number (entered by the user) - required product or spare part amount (user-defined) 73 delivery date (user-defined) A diagram of an order, its entries and relationships with items is shown in figure . Figure 5.8-1 Order Order Data Model The relationship between an order, its entries and items can be shown as the data model in the figure Figure 5.8-2 Order model 74 . 5.9 Order Planning Objectives: Cílem kapitoly je ukázat algoritmy pro naplánování zakázky v čase a množství. Keywords: Order; Order Planning Planning an order is similar to defining of quantities in the bill of materials. In addition to that, however, it must take account of due dates of order entries. One item may occer multiple times with different due dates of production requirements or different purchase dates. Planning Algorithm The process starts with order entries, which the program uses for generating requirements with assigned dates. From these requirements, the one with the lowest level code is selected and its production order or ordering requirement is generated and a date assigned. The program uses a single level explosion of these production orders to generate further requirements for production of parts with due dates, taking account of their production times based on the routing. Relationship between Production Requirement and Production Oder It is possible to meet requirements in various ways. Only some are listed: one requirement = one production order (typical method) multiple requirements = single production order (grouping) single requirement = multiple production orders (batch sizing) single requirement = one or more production orders with identical amounts (fixed batch size) Batch sizing is used when the required amount exceeds the maximum quantity suitable for production This algorithm prevents long-term blockages of critical workstations. Grouping: if one item occurs multiple times within the grouping range, a production order or ordering requirement is generated, covering multiple requirements. In this case, the required date is set to the earliest of required dates of all the grouped requirements. Fixed batch size is applied if, for instance, a workstation with fixed capacity is used (furnaces, surface treatments). Example of Planning Figure shows how the times are planned for an order using the above bill of materials. Individual item requirements are noted on the time axis. On each axis, the requirements are marked with solid down arrows. Production orders and ordering requirements are shown as solid up arrows. Links of the bill of materials are displayed as diagonal dashed arrows between time axes of individual items. These dashed arrows also represent manufacturing and ordering lead times of parts. Algorithm Implementation The algorithm runs as follows: First, the requirements resulting from the order are marked on the time axes: two A products needed in 20 days from now, one spare part needed in 13 days from now and 2 spare parts required in 20 days from now. The A product shall be exploded (as its low-level code is the lowest value). 2*2 = 4 pieces of the C assembly are required in 19 days and four B parts are needed in 19 days from now. 75 The procedure is repeated with further items according to their low level code values. Grouping is used for the E assembly: one piece is required in 13 days from now and 12 pieces are needed in 16 days from now. A production order issued in 13 days from now shall cover both requirements. Further grouping is used with the I material. It is necessary to submit an order for materials purchasing: four D-parts must be purchased in 14 days from now, fifteen I pieces shall be purchased 9 days from now, thirty-nine J pieces in 7 days from now, twelve F parts in 16 days from now, four 4 parts in 14 days from now and sixteen H parts in 15 days from now. Time planning of orders, together with accounting, represent essential functionalities of business information systems. Figure 5.9-1 Planning an order Daný obrázek si lze prohlédnout také jako animaci. MRP II 76 6 Production Data Representation in Access Students should know the basics of working with the ACCESS database system (tables, queries, macros, forms and reports), such as that obtained in the PP01 course: Introduction to Data Processing. The text is based on the TPV.mdb database, which is available as part of the PP02 course. Objectives: The purpose of this chapter is to create bill of materials and production routing representations in ACCESS DB. Keywords: Bill of Materials; Bill of materials link; Manufactured item; Operation; Purchased item; Technological routing; Workstation; 6.1 Tables Objectives: This article will demonstrate an ACCESS database system data model of the technical preparation of production. You will create tables and fill in them with test data. Keywords: Bill of materials link; Item; Operation; Table; Workstation; Tables Table Structure Table structure was created in the ACCESS database system: see figure . The Items, Operations, BOMlinks and Workstations tables are based on the preceding analysis. The Parameters (Params - because of SQL keyword) table is an auxiliary one, storing a single variable: the working level code. The XItems table is an auxiliary one and serves for storing intermediate results of calculations of times and prices based on routings. 77 Figure 6.1-1 Table structure Note that the Items table occurs twice within the model. This results from the role of the item in a bill of materials: higher-level item lower-level item Note: It is not allowed to use diacritical signs for identifiers in the ACCESS database system. Data identifiers may only be described with characters with no diacritical signs. The Items Table The structure of the Položky (Items) table is shown in figure 78 . Figure 6.1-2 Structure of the Items table Indices of the Položky (Items) table are shown in figure . Figure 6.1-3 Indices of the Items table The Items table has been filled with initial data . 79 Figure 6.1-4 Initial contents of the Items table The BOM Links Table The structure of the KsvVazby table is shown in figure . Figure 6.1-5 Structure of the BOMLinks table Indices of the BOM Links table are shown in figure . 80 Figure 6.1-6 Indices of the BOMLinks table The BOM Links table has been filled with initial data . Figure 6.1-7 Initial contents of the BOMLinks table The Workstations Table 81 The structure of the Workstations table is shown in figure . Figure 6.1-8 Structure of the Workstations table Indices of the Workstations table are shown in figure . Figure 6.1-9 Indices of the Workstations table The Workstations table has been filled with initial data . Note: Because of the length of the workstation name (8 bytes) Locksmith is abbreviated to Locsmith. Figure 6.1-10 Initial contents of the Workstations table 82 The Operations Table The structure of the Operations table is shown in figure . Figure 6.1-11 Structure of the Operations table Indices of the Operations table are shown in figure . Figure 6.1-12 Indices of the Operations table The Operations table has been filled with initial data 83 Figure 6.1-13 Initial contents of the Operations table XItems - Auxiliary Items Table The table is used in queries and macros, being filled in and cleared during the calculations. The structure of the XItems table is shown in figure . Figure 6.1-14 Structure of the XItems table The Params Table 84 The table holds auxiliary variables for calculations. The structure of the Params table is shown in figure . Figure 6.1-15 Structure of the Params table The Params table contains a single line with KeyParam = 1 and LowLevel = 0. 6.2 Simple Queries The actual processing is controlled by ACCESS macros. These macros launch individual queries. Therefore we shall describe all queries first (select, crosstab, make-table, update, append and delete). As there are many of them, they will be discussed in several articles. Objectives: The purpose of this article is to give a description of simple queries for tables. Keywords: Algoritm of processing; Query; Simple Queries Overview of Queries The list of all queries is figure . 85 Figure 6.2-1 Query listing Queries are used independently, calling one another or as part of macros performing complex planning. As there are many queries, they will be discussed across several articles. Items with No Routings The purpose of a select query is to find the items, which have no operations assigned. The grid of the query is shown in figure . 86 Figure 6.2-2 Items with no routing grid The corresponding SQL query is shown in figure . Figure 6.2-3 Items with no routing SQL Purchased Items with No Cost Assigned The purpose of a select query is to find the purchased items, which have no cost assigned. The query grid is shown in the figure . 87 Figure 6.2-4 Items with no cost assigned grid The corresponding SQL query is shown in the figure . Figure 6.2-5 Items with no cost assigned SQL Purchased Items with No Delivery Time The purpose of a select query is to find the purchased items, which have no times assigned. The grid of the query is shown in the figure . 88 Figure 6.2-6 Purchased Items with no Delivery Time grid The corresponding SQL query is shown in the figure . Figure 6.2-7 Purchased Items with no Delivery Time SQL Items with Routings The purpose of a select query is to find the items, which have operations assigned by mistake. The grid of the query is shown in the figure . 89 Figure 6.2-8 Purchased Items with Routing grid The corresponding SQL query is shown in figure . Figure 6.2-9 Purchased Items with Routing SQL 6.3 Queries for Cost Calculation Based on the Routing Objectives: The purpose of this process is to calculate the price based on the routing. Keywords: Algoritm of processing; Query; Queries for Cost Calculation Based on the Routing Let us take a look at the figure . 90 The routing-based price is a sum of prices of operations: The price of an operation is a product of the operation duration and the workstation rate. Duration of an operation is a sum of its preparation time and the processed quantity multiplied by the unit time. Figure 6.3-1 Determination of operations' prices Cost Calculation of Operations As this calculation is similar to finding the duration of the operation, we will calculate the duration of the operation together with its cost. The grid of the query is shown in the figure . 91 Figure 6.3-2 Operation cost and time grid The corresponding SQL query is shown in figure . Figure 6.3-3 Operation cost and time SQL The result of the query is shown in the figure . 92 Figure 6.3-4 Operation cost and time result Summary Cost Calculation of Operations in the Routing The calculation be performed as a summary query on the previous query. The grid of the query is shown in the figure . Figure 6.3-5 Sum of Operation cost and time grid 93 The corresponding SQL query is shown in figure . Figure 6.3-6 Sum of Operation cost and time SQL The result of the query is shown in the figure . Figure 6.3-7 Sum of Operation cost and time result Append Query for Auxiliary Items It is not possible to enter the result of the preceding query directly into the item table (ACCESS property). Therefore, an append query will be used to save the result in the auxiliary item table (XItems). Then, an update query will be used to transfer it to the Items table. Finally, the XItems will be cleared. The grid of the append query is shown in the figure . 94 Figure 6.3-8 Append query grid The corresponding SQL query is shown in figure . Figure 6.3-9 Append query SQL The result of the append query is an auxiliary table of an item - XItems 95 . Figure 6.3-10 Append query result Transfer of Duration and Cost from an Auxiliary Table of Items to the Item Table The grid of the update query is shown in the figure . Figure 6.3-11 Update query grid The corresponding SQL update query is shown in the figure 96 . Figure 6.3-12 Update query SQL Upon the preceding operation, the routing-based price and lead time values will be updated. The result of the update query in the Items table is shown in figure . Figure 6.3-13 Update query result 97 Figure 6.3-14 Update query result Delete Query for Cancelling All Data in the Auxiliary Item Table Finally, the delete query will be used for clearing the XItems. The grid of the delete query is shown in the figure . Figure 6.3-15 Delete query grid 98 The corresponding SQL delete query is shown in figure . Figure 6.3-16 Delete query SQL 6.4 Planning Queries Objectives: The purpose of this article is to demonstrate planning queries with a bill of materials. Keywords: Algoritm of processing; Query; Planning Queries An Update Query on Bill of Materials Planning: Transfer of Ordered Items to Planned Items The update query transfers the ordered amount to the planned amount of item. The grid of the query is shown in the figure . 99 Figure 6.4-1 Ordered Amount to Planned Amount grid The corresponding SQL query is shown in figure . Figure 6.4-2 Ordered Amount to Planned Amount SQL Intermediate Step of Calculation of Levels - Adding to Auxiliary Items All items produced by single level explosions of higher-level items shall be included in the table containing auxiliary items and assigned the level equal to that listed in the parameter table. The grid of the query is shown in the figure . 100 Figure 6.4-3 Level Calculation Append query grid The corresponding SQL query is shown in figure . Figure 6.4-4 Level Calculation Append query SQL Intermediate Step of Level Calculation - Copying the Low Level Data from Auxiliary Items to Proper Items The grid of the query is shown in the figure . 101 Figure 6.4-5 Level from XItems to Items grid The corresponding SQL query is shown in . Figure 6.4-6 Level from XItems to Items SQL Intermediate Step in Time-Planning of Items The grid of the query is shown in the figure . 102 Figure 6.4-7 Time Planning Update query grid The corresponding SQL query is shown in figure . Figure 6.4-8 Time Planning Update query SQL Intermediate Step in Planning Quantities The grid of the query is shown in the figure . 103 Figure 6.4-9 BOM Explosion Update query grid The corresponding SQL query is shown in figure . Figure 6.4-10 BOM Explosion Update query SQL Intermediate Step in Price Calculation The grid of the query is shown in the figure . 104 Figure 6.4-11 Cost Counting Update query grid The corresponding SQL query is shown in . Figure 6.4-12 Cost Counting Update query SQL 6.5 Auxiliary Queries for Planning Objectives: The purpose of the article is to supply the remaining planning queries. Keywords: Algoritm of processing; Query; 105 Auxiliary Queries for Planning Update Query for Zeroing the Time and Cost Data of the Routing Items The purpose of this update query is to set to zero the following entries of manufactured items: total lead time lead time item price routing-based price The grid of the query is shown in the figure . Figure 6.5-1 Reset Time and Cost grid The corresponding SQL query is shown in figure . Figure 6.5-2 Reset Time and Cost SQL Update Query for Zeroing the Planning Data Of The Bill Of Materials Items 106 The purpose of this update query is to zero the following entries of all items: total lead time planned amount level code The grid of the query is shown in the figure . Figure 6.5-3 Reset BOM Data grid The corresponding SQL query is shown in figure . Figure 6.5-4 Reset BOM Data SQL Group of Update Queries for Setting Auxiliary Local Variables in the Parametry Table Setting the level to 0 The grid of the query is shown in the figure . 107 Figure 6.5-5 Set Level to 0 grid The corresponding SQL query is shown in figure . Figure 6.5-6 Set Level to 0 SQL Setting the Level to 6 The grid of the query is shown in the figure . Figure 6.5-7 Set Level to 6 grid 108 The corresponding SQL query is shown in figure . Figure 6.5-8 Set Level to 6 SQL Setting to Higher Level The grid of the query is shown in the figure . Figure 6.5-9 Set to Higher Level grid The corresponding SQL query is shown in figure . Figure 6.5-10 Set to Higher Level SQL Setting to Lower Level The grid of the query is shown in the figure . 109 Figure 6.5-11 Set to Lower Level grid The corresponding SQL query is shown in figure . Figure 6.5-12 Set to Lower Level SQL 6.6 Macros Objectives: The purpose of this article is to demonstrate automation of processing by merging queries into macros. Keywords: Algoritm of processing; Makro; Makros With macros it is possible to merge individual queries to form a comprehensive processing operation. A survey of macros is in figure . 110 Figure 6.6-1 Survay of Macros For launching macros, it is convenient to switch off confirmation of action queries. Otherwise you may have to confirm queries up to several hundred times during planning . 111 Figure 6.6-2 Not confirm Action Queries and Changes In order to work with the bill of materials, you can circumvent the use of a cycle, which can be implemented as a macro sequence for increasing or decreasing levels (for simplicity you may consider no more than 5 BOM levels). Macro: Zeroing the Planning Data The purpose of the macro is to merge the queries for zeroing the time, price and BOM data in the item table. The macro including its details is shown in figure . 112 Figure 6.6-3 Macro Reset Planning Data The result is shown in figure . Figure 6.6-4 Planning Data have been Reset Makro Aktualizace doby a ceny 113 Cílem makra je aktualizace doby výroby a ceny položek z technologických postupů. Makro včetně detailů je na obr. . Figure 6.6-5 Macro Set Cost and Time The result is shown in figure . Figure 6.6-6 Time and Cost have been Updated 114 Macro: Calculating the Level The purpose of this macro is to calculate an item level in the bill of materials. The macro including its details is shown in figure . Figure 6.6-7 Macro Low Level Calculation The result is shown in figure . 115 Figure 6.6-8 Low Level calculated Macro: Time-Planning The purpose of this macro is to calculate the time-plan of an item in the bill of materials. The macro including its details is shown in figure . Figure 6.6-9 Macro Time Planning 116 The result is shown in figure . Figure 6.6-10 Times planned Macro: Calculation of Cost in the Bill of Materials The purpose of this macro is to calculate the price of an item in the bill of materials. The macro is shown in figure . Figure 6.6-11 Macro Cost in BOM Calculation 117 The result is shown in figure . Figure 6.6-12 Cost in BOM Calculated Macro: Bill of Materials Explosion - Calculation of Quantities The purpose of this macro is to calculate the amount of an item in the bill of materials. The macro is shown in figure . 118 Figure 6.6-13 Macro BOM Explosion The result is shown in figure . Figure 6.6-14 Amount in BOM Calculated 119 6.7 Reports Keywords: Report; Reports To get a good view of the data, it is possible to produce reports. Report of Items Part of the report of items is shown in figure . . Figure 6.7-1 Report of Items Report of Links of the Bill of Materials The report is shown in figure . 120 Figure 6.7-2 Report of BOM Links Reports of Workstations The report is shown in figure . Figure 6.7-3 Report of Workstations Report of a Technological Routing The report is shown in figure . 121 Figure 6.7-4 Report of Routings 6.8 Forms Keywords: Form; Forms Control Form The control form links individual elements of the database interface. Individual buttons serve for calling further forms, reports, data sheets and processing. 122 Figure 6.8-1 Control Form Below, examples of simple forms will be shown. The Items Form An example of a simple form for processing items is shown in fig. 123 . Figure 6.8-2 Items Form The BOM Links Form An example of a simple form for processing BOM links is shown in fig . Figure 6.8-3 BOM Links Form The Workstations Form An example of a simple form for processing workstations is shown in fig. 124 . Figure 6.8-4 Workstations Form The Operations Form An example of a simple form for processing operations is shown in fig. Figure 6.8-5 Operations Form The Routings Form An example of a simple form for processing operations is shown in fig. . 125 Figure 6.8-6 Routings Form 126