The document discusses abstract data types (ADTs), specifically queues. It defines a queue as a linear collection where elements are added to one end and removed from the other end, following a first-in, first-out (FIFO) approach. The key queue operations are enqueue, which adds an element, and dequeue, which removes the element that has been in the queue longest. Queues can be implemented using arrays or linked lists. Array implementations use head and tail pointers to track the start and end of the queue.
The document discusses abstract data types (ADTs), specifically queues. It defines a queue as a linear collection where elements are added to one end and removed from the other end, following a first-in, first-out (FIFO) approach. The key queue operations are enqueue, which adds an element, and dequeue, which removes the element that has been in the queue longest. Queues can be implemented using arrays or linked lists.
The document discusses arithmetic expressions and how to evaluate them using stacks. It defines arithmetic expressions and their components. It then describes the rules for evaluating expressions, including order of operations. Different notation styles for expressions are introduced - infix, prefix and postfix. An algorithm is provided for converting infix expressions to postfix notation using a stack. Finally, the document explains how to evaluate a postfix expression using a stack.
This document discusses top-down parsing and LL parsing. It begins by defining top-down parsing as discovering a parse tree from top to bottom using a preorder traversal and leftmost derivation. It then explains that LL parsing is a technique of top-down parsing that uses a parser stack, parsing table, and driver function. It identifies left recursion and left factoring as problems for LL(1) parsers, as they prevent deterministic parsing. It provides examples of eliminating left recursion and left factoring through grammar transformations.
Lisp has several basic data types including numbers, characters, symbols, lists, arrays, hash tables, and functions. Numbers can be integers, ratios, reals, complexes, and floats. Characters are basic text elements. Symbols are names that can have properties. Lists are sequences of conses (two-element records) linked together. Arrays store elements in a grid structure. Hash tables efficiently map keys to values. Functions represent procedures that can be invoked. Common Lisp provides various functions and constructs for manipulating these basic data types as data structures.
This document discusses top-down parsing and LL parsers. It provides an introduction to top-down parsing and describes how it works by hypothesizing general parse tree structures and checking compatibility with known structures. It also discusses LL parsers and how they use a top-down parsing strategy. Finally, it covers recursive descent parsing, predictive parsing, building a predictive parsing table using FIRST and FOLLOW functions, and how a non-recursive predictive parser works by consulting a parsing table.
Dr Nisha Arora's document provides an overview of data types and operators in R. It discusses variable assignment, numerical and relational operators, logical operators, built-in mathematical and trigonometric functions, data types including logical, numeric, integer, complex and character, coercion, infinity (Inf), Not A Number (NaN), and Not Available (NA) values. It also covers handling of missing values using functions like is.na(), complete.cases(), mean(na.rm=TRUE). The document provides resources for further learning including books, blogs, communities and online courses to learn R coding.
R supports various data types including numbers, strings, factors, data frames, and tables. Numbers and strings can be assigned to variables using <- or =. Factors represent discrete groupings. Lists are ordered collections of objects that can contain different data types. Data frames are lists that behave like tables, with each component being a vector of the same length. The table() function generates frequency tables from factors.
This document discusses top-down parsing and different types of top-down parsers, including recursive descent parsers, predictive parsers, and LL(1) grammars. It explains how to build predictive parsers without recursion by using a parsing table constructed from the FIRST and FOLLOW sets of grammar symbols. The key steps are: 1) computing FIRST and FOLLOW, 2) filling the predictive parsing table based on FIRST/FOLLOW, 3) using the table to parse inputs in a non-recursive manner by maintaining the parser's own stack. An example is provided to illustrate constructing the FIRST/FOLLOW sets and parsing table for a sample grammar.
The document discusses abstract data types (ADTs), specifically queues. It defines a queue as a linear collection where elements are added to one end and removed from the other end, following a first-in, first-out (FIFO) approach. The key queue operations are enqueue, which adds an element, and dequeue, which removes the element that has been in the queue longest. Queues can be implemented using arrays or linked lists.
The document discusses arithmetic expressions and how to evaluate them using stacks. It defines arithmetic expressions and their components. It then describes the rules for evaluating expressions, including order of operations. Different notation styles for expressions are introduced - infix, prefix and postfix. An algorithm is provided for converting infix expressions to postfix notation using a stack. Finally, the document explains how to evaluate a postfix expression using a stack.
This document discusses top-down parsing and LL parsing. It begins by defining top-down parsing as discovering a parse tree from top to bottom using a preorder traversal and leftmost derivation. It then explains that LL parsing is a technique of top-down parsing that uses a parser stack, parsing table, and driver function. It identifies left recursion and left factoring as problems for LL(1) parsers, as they prevent deterministic parsing. It provides examples of eliminating left recursion and left factoring through grammar transformations.
Lisp has several basic data types including numbers, characters, symbols, lists, arrays, hash tables, and functions. Numbers can be integers, ratios, reals, complexes, and floats. Characters are basic text elements. Symbols are names that can have properties. Lists are sequences of conses (two-element records) linked together. Arrays store elements in a grid structure. Hash tables efficiently map keys to values. Functions represent procedures that can be invoked. Common Lisp provides various functions and constructs for manipulating these basic data types as data structures.
This document discusses top-down parsing and LL parsers. It provides an introduction to top-down parsing and describes how it works by hypothesizing general parse tree structures and checking compatibility with known structures. It also discusses LL parsers and how they use a top-down parsing strategy. Finally, it covers recursive descent parsing, predictive parsing, building a predictive parsing table using FIRST and FOLLOW functions, and how a non-recursive predictive parser works by consulting a parsing table.
Dr Nisha Arora's document provides an overview of data types and operators in R. It discusses variable assignment, numerical and relational operators, logical operators, built-in mathematical and trigonometric functions, data types including logical, numeric, integer, complex and character, coercion, infinity (Inf), Not A Number (NaN), and Not Available (NA) values. It also covers handling of missing values using functions like is.na(), complete.cases(), mean(na.rm=TRUE). The document provides resources for further learning including books, blogs, communities and online courses to learn R coding.
R supports various data types including numbers, strings, factors, data frames, and tables. Numbers and strings can be assigned to variables using <- or =. Factors represent discrete groupings. Lists are ordered collections of objects that can contain different data types. Data frames are lists that behave like tables, with each component being a vector of the same length. The table() function generates frequency tables from factors.
This document discusses top-down parsing and different types of top-down parsers, including recursive descent parsers, predictive parsers, and LL(1) grammars. It explains how to build predictive parsers without recursion by using a parsing table constructed from the FIRST and FOLLOW sets of grammar symbols. The key steps are: 1) computing FIRST and FOLLOW, 2) filling the predictive parsing table based on FIRST/FOLLOW, 3) using the table to parse inputs in a non-recursive manner by maintaining the parser's own stack. An example is provided to illustrate constructing the FIRST/FOLLOW sets and parsing table for a sample grammar.
In this tutorial, we learn to create variables in R. Followed by that, we explore the different data types including numeric, integer, character, logical and date/time.
This document discusses top-down parsing and LL parsing. It begins with an overview of top-down parsing as discovering a parse tree from top to bottom using a preorder traversal and leftmost derivation. It then describes LL parsing as a technique of top-down parsing that uses a parser stack, parsing table, and driver function. It notes two problems for LL(1) parsers as left recursion and left factoring. Finally, it provides two examples of parsing strings using LL parsing.
Java 1.5 - whats new and modern patterns (2007)Peter Antman
JDK 1.5 introduced many new language features and patterns including generics, autoboxing, varargs, enums, enhanced for loops, and annotations. It also improved concurrency support and tools. Generics allow stronger typing by making collections type-safe. Autoboxing automates wrapping primitives for object-oriented code.
This document discusses stacks and queues as linear data structures. It defines stacks as last-in, first-out (LIFO) collections where the last item added is the first removed. Queues are first-in, first-out (FIFO) collections where the first item added is the first removed. Common stack and queue operations like push, pop, insert, and remove are presented along with algorithms and examples. Applications of stacks and queues in areas like expression evaluation, string reversal, and scheduling are also covered.
Predicates in Common Lisp are functions that test conditions and return true or false. There are different types of predicates including data type predicates to check types, equality predicates like eq and equal to compare objects, and logical operators like and, or, and not. Specific predicates test for individual data types like numberp, listp, symbolp. Subtypep checks if one type is a subtype of another.
The document discusses Lisp input and output functions. It describes how Lisp represents objects in printed form for input/output and the read function that accepts this printed input and constructs Lisp objects. It covers parsing of numbers, symbols, and macro characters. It also describes output functions like print, princ, and format for writing to streams, as well as input functions like read, read-line, and querying functions like y-or-n-p.
This document discusses predictive parsers, which are an efficient form of top-down parsing that does not require backtracking. It describes how to construct the transition diagram and parsing tables for a predictive parser from a given grammar. A predictive parser uses these tables to parse input strings in a non-recursive manner by tracking the stack contents and remaining input at each step.
This document discusses algorithms and their applications in computer science. It begins with acknowledging those who helped with a course on algorithms. It then provides an introduction to algorithms, describing them as step-by-step procedures for solving general problems. The document provides examples of algorithms for finding the maximum value in a list, searching for a value linearly, and sorting values with bubble sort. It concludes by describing a Java program that uses an algorithm to search for a value within an array.
Type specifiers in Common Lisp allow specifying the type of data. Standard type specifiers include symbols for types like number, string, array. Type specifiers can also be lists to further specify element types, dimensions, etc. New type specifiers can be defined using deftype. Functions like coerce and upgraded-array-element-type handle type conversions.
A bottom-up parser creates a parse tree starting from the leaves and working towards the root by finding the right-most derivation of the input string in reverse order. Bottom-up parsing involves two main actions: shift, which pushes the next input symbol onto a stack; and reduce, which pops symbols from the stack according to grammar rules. LR parsers are a type of bottom-up parser that can handle a wide range of grammars through the use of parsing tables constructed from the grammar to determine the shift and reduce actions.
This document discusses stacks and queues as data structures. It describes stacks as containers that follow the last-in first-out (LIFO) principle, allowing only push and pop operations. Queues are containers that follow the first-in first-out (FIFO) principle, allowing enqueue and dequeue operations. Examples of stack applications include reversing words and undo mechanisms. Pseudocode is provided for adding and removing items from both stacks and queues.
R is a widely used programming language for statistical analysis and graphics. It allows integration with other languages like C/C++ for efficiency. R includes features like conditionals, loops, functions, and data handling capabilities. It supports various data types including vectors, lists, matrices, arrays, factors and data frames. Variables can be assigned values and their data type changed. Operators include arithmetic, relational, logical and assignment operators. Functions are objects that perform specific tasks and are called with arguments. Strings are stored within double quotes. Vectors are basic data objects that can have single or multiple elements.
A little bit of Lamba Calculus.
What is that and how it is applied in functional programming languages.
Currying, High Order Functions, Anonymous Functions
1) Linear search, also called sequential search, is a simple algorithm that checks each element of a list sequentially to find a target value. It has a time complexity of O(n) in the worst case.
2) The best case for linear search is O(1) when the target is found at the first element. The worst case is O(n) when the target is at the end or not in the list at all.
3) Linear search requires only O(1) space since it only needs to store the target element being searched for, regardless of the size of the input list.
The document summarizes different searching and sorting algorithms. It discusses linear search and binary search for searching algorithms. It explains that linear search has O(n) time complexity while binary search has O(log n) time complexity. For sorting algorithms, it describes bubble sort, selection sort, and insertion sort. It provides pseudocode to illustrate how each algorithm works to sort a list or array.
This document provides an introduction to programming in Ruby. It discusses various Ruby concepts like numbers, strings, variables, and objects. Some key points covered include:
- How to use the interactive Ruby shell IRB and Ruby IDE Netbeans
- Common number methods in Ruby like addition, subtraction, multiplication, division, and conversions between integers and floats
- How strings can be manipulated using methods like upcase, downcase, capitalize, and reverse
- Using string interpolation to embed variable values inside strings
- Converting between strings, arrays, and ranges
- That variables in Ruby can hold different data types and are dynamically typed
This document discusses Java lists and iterators. It provides information on:
1) The List interface and classes that implement it like ArrayList and LinkedList. It also discusses how to create and output List objects.
2) Common List methods like isEmpty(), size(), add(), get(), and the iterator() method.
3) Using iterators to traverse List elements, including the iterator interface methods and how to use a generic iterator in a for-each loop.
4) Differences between using an iterator versus a for-each loop, where an iterator is needed to remove elements from the List.
Bitcoin’s blockchain - from hashes to Escrow and beyondGrzegorz Gawron
This document summarizes the key building blocks of Bitcoin's blockchain, including cryptographic hash functions, hash pointers, the Merkle tree, digital signatures, and transaction scripts. It discusses how hash functions are used to link blocks together in the blockchain and ensure data integrity. Transaction scripts allow for advanced applications like multisignature escrow, green addresses for third-party exchanges, and efficient micropayments. The challenges of bootstrapping consensus, 51% attacks, and changing the blockchain protocol through hard or soft forks are also outlined.
This document provides an overview of security and cryptography topics including:
- The basics of security including confidentiality, authenticity, integrity, and non-repudiation goals and how symmetric and asymmetric cryptography help achieve them.
- Symmetric cryptography algorithms like DES, Triple DES, and AES along with modes of operation like CBC.
- Asymmetric cryptography including key exchange with Diffie-Hellman and digital signatures with RSA and ECC.
- Cryptographic hash functions like SHA and their properties. Message authentication codes (MACs) that provide integrity.
- Public key infrastructure with certificates and how they establish authenticity of public keys.
- Attacks on algorithms, implementations, and protocols and the need for unpredictable
XML and Web Data discusses XML, its characteristics, elements, and schemas. XML is used to simplify data exchange between software agents. It uses tags like HTML but is extensible and has no predefined semantics. XML documents must be well-formed with properly nested elements. Namespaces are used to avoid naming conflicts, and attributes can specify element identifiers and references. XML schemas define rules for XML documents and support data types, complex elements, and integrity constraints.
HTML5 is the new standard for HTML that adds new semantic elements, canvas for drawing, video and audio elements, and form controls like date and color pickers. It is a collaboration between W3C and WHATWG to address changes to the web since 1999. Key features include new elements, canvas drawing, media playback with <video> and <audio> tags, offline web apps, and improved form controls. Browser support is increasing, though not fully implemented. Modernizr can detect support for HTML5 features.
In this tutorial, we learn to create variables in R. Followed by that, we explore the different data types including numeric, integer, character, logical and date/time.
This document discusses top-down parsing and LL parsing. It begins with an overview of top-down parsing as discovering a parse tree from top to bottom using a preorder traversal and leftmost derivation. It then describes LL parsing as a technique of top-down parsing that uses a parser stack, parsing table, and driver function. It notes two problems for LL(1) parsers as left recursion and left factoring. Finally, it provides two examples of parsing strings using LL parsing.
Java 1.5 - whats new and modern patterns (2007)Peter Antman
JDK 1.5 introduced many new language features and patterns including generics, autoboxing, varargs, enums, enhanced for loops, and annotations. It also improved concurrency support and tools. Generics allow stronger typing by making collections type-safe. Autoboxing automates wrapping primitives for object-oriented code.
This document discusses stacks and queues as linear data structures. It defines stacks as last-in, first-out (LIFO) collections where the last item added is the first removed. Queues are first-in, first-out (FIFO) collections where the first item added is the first removed. Common stack and queue operations like push, pop, insert, and remove are presented along with algorithms and examples. Applications of stacks and queues in areas like expression evaluation, string reversal, and scheduling are also covered.
Predicates in Common Lisp are functions that test conditions and return true or false. There are different types of predicates including data type predicates to check types, equality predicates like eq and equal to compare objects, and logical operators like and, or, and not. Specific predicates test for individual data types like numberp, listp, symbolp. Subtypep checks if one type is a subtype of another.
The document discusses Lisp input and output functions. It describes how Lisp represents objects in printed form for input/output and the read function that accepts this printed input and constructs Lisp objects. It covers parsing of numbers, symbols, and macro characters. It also describes output functions like print, princ, and format for writing to streams, as well as input functions like read, read-line, and querying functions like y-or-n-p.
This document discusses predictive parsers, which are an efficient form of top-down parsing that does not require backtracking. It describes how to construct the transition diagram and parsing tables for a predictive parser from a given grammar. A predictive parser uses these tables to parse input strings in a non-recursive manner by tracking the stack contents and remaining input at each step.
This document discusses algorithms and their applications in computer science. It begins with acknowledging those who helped with a course on algorithms. It then provides an introduction to algorithms, describing them as step-by-step procedures for solving general problems. The document provides examples of algorithms for finding the maximum value in a list, searching for a value linearly, and sorting values with bubble sort. It concludes by describing a Java program that uses an algorithm to search for a value within an array.
Type specifiers in Common Lisp allow specifying the type of data. Standard type specifiers include symbols for types like number, string, array. Type specifiers can also be lists to further specify element types, dimensions, etc. New type specifiers can be defined using deftype. Functions like coerce and upgraded-array-element-type handle type conversions.
A bottom-up parser creates a parse tree starting from the leaves and working towards the root by finding the right-most derivation of the input string in reverse order. Bottom-up parsing involves two main actions: shift, which pushes the next input symbol onto a stack; and reduce, which pops symbols from the stack according to grammar rules. LR parsers are a type of bottom-up parser that can handle a wide range of grammars through the use of parsing tables constructed from the grammar to determine the shift and reduce actions.
This document discusses stacks and queues as data structures. It describes stacks as containers that follow the last-in first-out (LIFO) principle, allowing only push and pop operations. Queues are containers that follow the first-in first-out (FIFO) principle, allowing enqueue and dequeue operations. Examples of stack applications include reversing words and undo mechanisms. Pseudocode is provided for adding and removing items from both stacks and queues.
R is a widely used programming language for statistical analysis and graphics. It allows integration with other languages like C/C++ for efficiency. R includes features like conditionals, loops, functions, and data handling capabilities. It supports various data types including vectors, lists, matrices, arrays, factors and data frames. Variables can be assigned values and their data type changed. Operators include arithmetic, relational, logical and assignment operators. Functions are objects that perform specific tasks and are called with arguments. Strings are stored within double quotes. Vectors are basic data objects that can have single or multiple elements.
A little bit of Lamba Calculus.
What is that and how it is applied in functional programming languages.
Currying, High Order Functions, Anonymous Functions
1) Linear search, also called sequential search, is a simple algorithm that checks each element of a list sequentially to find a target value. It has a time complexity of O(n) in the worst case.
2) The best case for linear search is O(1) when the target is found at the first element. The worst case is O(n) when the target is at the end or not in the list at all.
3) Linear search requires only O(1) space since it only needs to store the target element being searched for, regardless of the size of the input list.
The document summarizes different searching and sorting algorithms. It discusses linear search and binary search for searching algorithms. It explains that linear search has O(n) time complexity while binary search has O(log n) time complexity. For sorting algorithms, it describes bubble sort, selection sort, and insertion sort. It provides pseudocode to illustrate how each algorithm works to sort a list or array.
This document provides an introduction to programming in Ruby. It discusses various Ruby concepts like numbers, strings, variables, and objects. Some key points covered include:
- How to use the interactive Ruby shell IRB and Ruby IDE Netbeans
- Common number methods in Ruby like addition, subtraction, multiplication, division, and conversions between integers and floats
- How strings can be manipulated using methods like upcase, downcase, capitalize, and reverse
- Using string interpolation to embed variable values inside strings
- Converting between strings, arrays, and ranges
- That variables in Ruby can hold different data types and are dynamically typed
This document discusses Java lists and iterators. It provides information on:
1) The List interface and classes that implement it like ArrayList and LinkedList. It also discusses how to create and output List objects.
2) Common List methods like isEmpty(), size(), add(), get(), and the iterator() method.
3) Using iterators to traverse List elements, including the iterator interface methods and how to use a generic iterator in a for-each loop.
4) Differences between using an iterator versus a for-each loop, where an iterator is needed to remove elements from the List.
Bitcoin’s blockchain - from hashes to Escrow and beyondGrzegorz Gawron
This document summarizes the key building blocks of Bitcoin's blockchain, including cryptographic hash functions, hash pointers, the Merkle tree, digital signatures, and transaction scripts. It discusses how hash functions are used to link blocks together in the blockchain and ensure data integrity. Transaction scripts allow for advanced applications like multisignature escrow, green addresses for third-party exchanges, and efficient micropayments. The challenges of bootstrapping consensus, 51% attacks, and changing the blockchain protocol through hard or soft forks are also outlined.
This document provides an overview of security and cryptography topics including:
- The basics of security including confidentiality, authenticity, integrity, and non-repudiation goals and how symmetric and asymmetric cryptography help achieve them.
- Symmetric cryptography algorithms like DES, Triple DES, and AES along with modes of operation like CBC.
- Asymmetric cryptography including key exchange with Diffie-Hellman and digital signatures with RSA and ECC.
- Cryptographic hash functions like SHA and their properties. Message authentication codes (MACs) that provide integrity.
- Public key infrastructure with certificates and how they establish authenticity of public keys.
- Attacks on algorithms, implementations, and protocols and the need for unpredictable
XML and Web Data discusses XML, its characteristics, elements, and schemas. XML is used to simplify data exchange between software agents. It uses tags like HTML but is extensible and has no predefined semantics. XML documents must be well-formed with properly nested elements. Namespaces are used to avoid naming conflicts, and attributes can specify element identifiers and references. XML schemas define rules for XML documents and support data types, complex elements, and integrity constraints.
HTML5 is the new standard for HTML that adds new semantic elements, canvas for drawing, video and audio elements, and form controls like date and color pickers. It is a collaboration between W3C and WHATWG to address changes to the web since 1999. Key features include new elements, canvas drawing, media playback with <video> and <audio> tags, offline web apps, and improved form controls. Browser support is increasing, though not fully implemented. Modernizr can detect support for HTML5 features.
Game Theory was used to analyze the feasibility of the 1980s Strategic Defense Initiative (SDI) or "Star Wars" program. The analysis found a 1/3 probability that the defensive system ("Blue") could defend against attacks. Game Theory was founded by mathematician John von Neumann, who was born in Budapest in 1903 and died in Washington D.C. in 1957.
1. Hash tables are good for random access of elements but not sequential access. When records need to be accessed sequentially, hashing can be problematic because elements are stored in random locations instead of consecutively.
2. To find the successor of a node in a binary search tree, we take the right child. This operation has a runtime complexity of O(1).
3. When comparing operations like insertion, deletion, and searching between different data structures, arrays generally have the best performance for insertion and searching, while linked lists have better performance for deletion and allow for easy insertion/deletion anywhere. Binary search trees fall between these two.
The document discusses data structures and provides examples of common data structures like stacks, queues, trees, graphs. It defines key concepts like abstract data types and how they are implemented. It provides examples of applications of stacks, like for recursion, converting infix to postfix notation, validating expressions. It also discusses common problems like towers of Hanoi and N-Queens that can be solved using concepts like backtracking and data structures like stacks.
1) The document discusses various data structures and algorithms including arrays, stacks, queues, pointers, and linked lists.
2) It provides details on common data structure operations like insertion, deletion, sorting, and searching. Linear and non-linear data structures are described.
3) Examples of how each data structure works are given, such as the push and pop operations for stacks, and insertion and deletion for queues. Applications like arithmetic expressions and recursion are discussed.
This document provides an overview of data structures and algorithms. It defines data structures as organized storage for data that allows for efficient access and updating. There are two main categories of data structures - linear and non-linear. Common linear data structures include arrays and linked lists, while trees and graphs are examples of non-linear data structures. The document then focuses on array data structures, providing details on one-dimensional and two-dimensional arrays including representation, insertion, deletion, and traversal algorithms. It also covers common abstract data types like stacks and queues.
This document provides an overview of data structures and algorithms. It defines data structures as a way to store and organize data for efficient access and updating. There are two main categories of data structures - linear and non-linear. Common linear data structures include arrays and linked lists, while trees and graphs are examples of non-linear data structures. The document also describes common operations for stacks and queues like push, pop, enqueue and dequeue. It concludes by discussing different notations for writing arithmetic expressions like infix, prefix and postfix notations.
1. A stack is a linear data structure that follows the LIFO (Last In First Out) principle, where the last item inserted is the first item removed. It allows insertion and removal of items from one end only.
2. Stacks have many applications including function calls, memory allocation, undo operations, and parsing expressions. They use push and pop operations to insert and remove items.
3. A queue is a linear data structure that follows the FIFO (First In First Out) principle, where the first item inserted is the first item removed. It allows insertion at one end (rear) and removal from the other (front). Queues are useful for scheduling processes.
A data structure is a way of storing data in computer memory so that it can be retrieved and manipulated efficiently. There are two main categories of data structures: linear and non-linear. Linear data structures include arrays, stacks, and queues where elements are stored in a linear order. Non-linear structures include trees and graphs where elements are not necessarily in a linear order. Common operations on data structures include traversing, searching, insertion, deletion, sorting, and merging. Algorithms use data structures to process and solve problems in an efficient manner.
This chapter discusses different data structures and their applications. It begins with classifying data structures as primitive and non-primitive. Common linear data structures like stacks, queues, and linked lists are described. Stacks follow LIFO while queues follow FIFO. Linked lists use nodes connected by pointers. The chapter provides examples of implementing operations for these structures.
This document discusses various data structures and their implementations in C++ using templates. It begins by reviewing basic linear data structures like lists, stacks, and queues. It then covers implementing these structures using array-based and linked representations in C++. Specifically, it describes how to implement lists, stacks, and queues using templates and both array and linked representations. It also compares the performance of array vs linked implementations.
This document discusses stacks as an abstract data type (ADT) and their implementation in Java. It begins by defining an ADT as having a specific interface of operations and axioms defining the semantics of those operations. Stacks are introduced as a LIFO data structure that supports push, pop, and top operations. The document then discusses implementing a stack interface in Java using exceptions to handle errors. It provides an example array-based stack implementation in Java using an array and index to track elements. Finally, it discusses an application of stacks to efficiently compute the span of stock price changes over time by using a stack to track previous higher prices.
This document provides an overview of priority queues and binary trees as data structures. It discusses:
1) The implementation of a priority queue using an array, including methods for insertion, removal, and checking length. The priority queue removes elements based on priority rather than FIFO order.
2) Issues with the array implementation for large data sets, and introducing an alternative tree implementation.
3) An introduction to binary trees as a non-linear data structure, providing examples like a family tree. Binary trees partition the data into a root node and left/right subtrees.
Data structures like stacks, queues, and priority queues can be implemented in Python using built-in data types and modules. Stacks follow LIFO order, with new items added to the top and removed from the top. Queues follow FIFO order, with new items added to the back and removed from the front. Priority queues order items by priority, so the highest or lowest priority item is removed first depending on the implementation.
This document provides a practical manual on data structures for computer science students. It was prepared by Mr. Naveen Choudhary and Dr. Dharm Singh of the Computer Science and Engineering department at Maharana Pratap University of Agriculture and Technology in Udaipur. The 138-page manual contains exercises and solutions to help students understand data structures from an applied perspective. It covers topics like stacks, queues, linked lists, trees, and sorting and searching algorithms.
This document discusses the introduction to data structures and algorithms. It covers course objectives including learning basic data structures like stacks and abstract data types. It defines abstract data types and lists the stack abstract data type. It provides examples of stack operations and applications. It demonstrates using a Stack class in Java and limitations/idioms when using stacks. It poses an exercise to use a stack to check if parentheses and curly brackets are balanced in a string. Finally, it discusses Eclipse concepts like the workspace, projects, and perspectives.
This document discusses different implementations of stacks and queues using linked lists and arrays. It describes how to implement a stack using a linked list, with push and pop operations adding and removing nodes from the front of the list. Queues are described as first-in first-out data structures, with enqueue adding to the back and dequeue removing from the front. Examples are given of using stacks and queues for applications like balancing parentheses in expressions and evaluating postfix notation.
The document discusses various list operations like add, remove, find, and get implemented using an array. It explains how each operation works by modifying the array and current pointer. For example, the add operation first shifts existing elements to make space and then inserts the new element. The remove operation removes the current element and shifts remaining elements left. The find operation searches the array and sets current to the found position.
C++ STL (quickest way to learn, even for absolute beginners).pptxGauravPandey43518
C++ STL is a collection of containers and algorithms that provide common programming tasks. It includes data structures like vector, set, map as well as sorting and searching algorithms. Using STL containers makes code shorter, faster and more error-free compared to manually writing these routines. STL is important for learning advanced C++ concepts like graphs and algorithms.
Chp-1 Quick Review of basic concepts.pdfSolomonMolla4
The document provides an overview of algorithms and their analysis. It defines an algorithm as a well-defined computational procedure that takes inputs and produces outputs. Algorithms solve computational problems by describing specific procedures to achieve the desired input-output relationship. Sorting is used as an example problem, with the goal of reordering a sequence into ascending order. Algorithm analysis focuses on predicting resource needs like time based on input size. For insertion sort, the best case is a sorted input (linear time) and worst case is reverse sorted (quadratic time). Worst case analysis is preferred as it provides an upper bound and models common or average cases.
The greedy choice at each step is to select the talk that ends earliest among the compatible options. This maximizes the chance of fitting additional talks into the schedule.
This document discusses techniques for deterministic replay of multithreaded programs. It describes how recording shared memory ordering information can enable replay that reproduces data races and concurrency bugs. Specifically, it outlines using a directory-based approach to track read-write dependencies between threads and reduce the log size through transitive reduction of dependencies.
Multi-threaded processor architectures can improve parallelism at both the instruction-level and thread-level. Simultaneous multi-threading (SMT) allows multiple threads to issue and execute instructions simultaneously by dynamically sharing processor resources. SMT reduces underutilization of functional units and improves performance over multiprocessors. Multi-threaded designs are well-suited for digital signal processing applications that can benefit from parallel execution at multiple levels. Examples of multi-threaded real-time operating systems that support parallel DSP applications are discussed.
Recursion involves functions that call themselves during execution. This document discusses recursive functions like factorial, Fibonacci sequence, power, and printing patterns. Recursive functions have a base case that stops the recursion. The factorial function is defined recursively as n! = n * (n-1)!, and this recursive definition is evaluated step-by-step for fact(4). Recursive functions can also be used to define sequences like Fibonacci numbers.
The document provides an overview of business analytics (BA) including its history, types, examples, challenges, and relationship to data mining. BA involves exploring past business performance data to gain insights and guide planning. It can focus on the business as a whole or segments. Types of BA include descriptive analytics like reporting, affinity grouping, and clustering, as well as predictive analytics. Challenges to BA include acquiring high quality data and reacting to data quickly. Data mining is important for BA as it helps handle large datasets and specific problems.
The document discusses data mining and knowledge discovery from large data sets. It begins by defining the terms data, information, knowledge, and wisdom. It then explains that the growth of data from various sources has created a need for data mining to extract useful knowledge from large data repositories. Data mining involves non-trivial analysis of implicit patterns in large data sets. It is an interdisciplinary field that draws from areas like machine learning, statistics, database technology, and visualization. The goal is to transform data into actionable information through an iterative process of identifying problems, mining data, acting on results, and measuring impact.
The document discusses memory hierarchy and cache performance. It introduces the concept of memory hierarchy to get the best of fast and large memories. It then discusses different memory technologies like SRAM, DRAM and disk and their access times. It explains the basic concepts of direct mapped cache, cache hits, misses and different ways to reduce miss penalties like using multiple cache levels. Finally, it classifies cache misses into compulsory, capacity and conflict misses and how these are affected based on cache parameters.
- Decision trees are a supervised learning technique used for classification problems. They work by recursively splitting a dataset based on the values of predictor variables and assigning class labels to the terminal nodes.
- The document describes how decision trees are constructed by starting with the entire training set at the root node and then successively splitting the data into purer child nodes based on attribute values. Attribute selection at each node is done using an impurity-based heuristic like information gain.
This document discusses how Analysis Services caching works and provides strategies for warming the Storage Engine cache and Formula Engine cache. It explains that the Storage Engine handles data retrieval from disk while the Formula Engine determines which data is needed for queries. Caching can improve performance but requires consideration of memory usage, cache structures, and data granularity. The document recommends using the CREATE CACHE statement and running regular queries to pre-populate the caches, while being mindful of how security and non-deterministic elements can impact cache sharing and scoping. Automating cache warming through SQL Server Agent jobs or SSIS packages is suggested.
Optimizing shared caches in chip multiprocessorsJames Wong
Chip multiprocessors, which place multiple processors on a single chip, have become common in modern processors. There are different approaches to managing caches in chip multiprocessors, including private caches for each processor or shared caches. The optimal approach balances factors like interconnect traffic, duplication of data, load balancing, and cache hit rates.
The document discusses non-uniform cache architectures (NUCA), cache coherence, and different implementations of directories in multicore systems. It describes NUCA designs that map data to banks based on distance from the controller to exploit non-uniform access times. Cache coherence is maintained using directory-based protocols that track copies of cache blocks. Directories can be implemented off-chip in DRAM or on-chip using duplicate tag stores or distributing the directory among cache banks.
This document discusses abstract data types (ADTs) and their implementation in various programming languages. It covers the key concepts of ADTs including data abstraction, encapsulation, information hiding, and defining the public interface separately from the private implementation. It provides examples of ADTs implemented using modules in Modula-2, packages in Ada, classes in C++, generics in Java and C#, and classes in Ruby. Parameterized and encapsulation constructs are also discussed as techniques for implementing and organizing ADTs.
This document discusses the key concepts of object-oriented programming including abstraction, encapsulation, classes and objects. It defines abstraction as focusing on the essential characteristics of an object and hiding unnecessary details. Encapsulation hides the implementation of an object's methods and data within its class. A class defines both the data and behaviors of an object through its public interface and private implementation. Objects are instantiations of classes that come to life through constructors and die through destructors while maintaining data integrity.
The document proposes optimizing DRAM caches for latency rather than hit rate, as previous work had done. It presents the Alloy Cache design which avoids serializing tag and data accesses, keeping them in the same DRAM row for lower latency. Using a simple Memory Access Predictor (MAP), Alloy Cache can predict whether to use a higher-latency serial access model or lower-latency parallel model. With MAP, Alloy Cache outperforms previous designs like SRAM-tag caches with fewer optimizations that degrade performance. The document advocates revisiting DRAM cache designs given their different constraints compared to SRAM caches.
The document discusses the key elements of the object model, including abstraction, encapsulation, modularity, and hierarchy. It explains that abstraction is one of the fundamental ways to cope with complexity in software design. Abstraction focuses on the essential characteristics of an object that distinguish it from other objects, from the perspective of the viewer. The object model provides a conceptual framework for object-oriented programming that is based on these elements.
Abstract classes and interfaces allow for abstraction and polymorphism in object-oriented design. Abstract classes can contain both abstract and concrete methods, while interfaces only contain abstract methods. Abstract classes are used to provide a common definition for subclasses through inheritance, while interfaces define a contract for implementing classes to follow. Both support polymorphism by allowing subclasses/implementing classes to determine the specific implementation for abstract methods.
Object-oriented analysis and design (OOAD) emphasizes investigating requirements rather than solutions, and conceptual solutions that fulfill requirements rather than implementations. OOAD focuses on identifying domain concepts and defining software objects and how they collaborate. The Unified Process includes inception, elaboration, construction, and transition phases with iterations and milestones leading to final product releases.
The document discusses several programming paradigms including single process, multi process, and multi-core/multi-thread. It then covers topics such as processes, threads, synchronization, and liveness issues in concurrent programming including deadlock, starvation and livelock. Processes run independently while threads share data and scheduling. Synchronization prevents interference and inconsistencies between threads accessing shared data. Liveness issues can cause programs to halt indefinitely.
The document provides information on three programming languages: COBOL, LISP, and Python. COBOL was released in 1959 and was used for 80% of business transactions due to its reliability. LISP was the second high-level language created in 1958 and introduced innovations like garbage collection and recursion using linked lists. Python was developed in the 1990s and prioritizes readability through features like whitespace and a simple grammar.
This document discusses inheritance in object-oriented programming. It explains that inheritance allows a subclass to inherit attributes and behaviors from a superclass, extending the superclass. This allows for code reuse and the establishment of class hierarchies. The document provides an example of a BankAccount superclass and SavingsAccount subclass, demonstrating how the subclass inherits methods like deposit() and withdraw() from the superclass while adding its own method, addInterest(). It also discusses polymorphism and access control as related concepts.
This document provides an overview of APIs, including what they are, why they are useful, common data formats like JSON and XML, RESTful API design principles, and how to consume and create APIs. It discusses API concepts like resources, HTTP verbs, caching, authentication, and error handling. It also provides examples of consuming APIs with tools like Postman and creating a simple API in Node.js.
Northern Engraving | Nameplate Manufacturing Process - 2024Northern Engraving
Manufacturing custom quality metal nameplates and badges involves several standard operations. Processes include sheet prep, lithography, screening, coating, punch press and inspection. All decoration is completed in the flat sheet with adhesive and tooling operations following. The possibilities for creating unique durable nameplates are endless. How will you create your brand identity? We can help!
Freshworks Rethinks NoSQL for Rapid Scaling & Cost-EfficiencyScyllaDB
Freshworks creates AI-boosted business software that helps employees work more efficiently and effectively. Managing data across multiple RDBMS and NoSQL databases was already a challenge at their current scale. To prepare for 10X growth, they knew it was time to rethink their database strategy. Learn how they architected a solution that would simplify scaling while keeping costs under control.
In the realm of cybersecurity, offensive security practices act as a critical shield. By simulating real-world attacks in a controlled environment, these techniques expose vulnerabilities before malicious actors can exploit them. This proactive approach allows manufacturers to identify and fix weaknesses, significantly enhancing system security.
This presentation delves into the development of a system designed to mimic Galileo's Open Service signal using software-defined radio (SDR) technology. We'll begin with a foundational overview of both Global Navigation Satellite Systems (GNSS) and the intricacies of digital signal processing.
The presentation culminates in a live demonstration. We'll showcase the manipulation of Galileo's Open Service pilot signal, simulating an attack on various software and hardware systems. This practical demonstration serves to highlight the potential consequences of unaddressed vulnerabilities, emphasizing the importance of offensive security practices in safeguarding critical infrastructure.
Essentials of Automations: Exploring Attributes & Automation ParametersSafe Software
Building automations in FME Flow can save time, money, and help businesses scale by eliminating data silos and providing data to stakeholders in real-time. One essential component to orchestrating complex automations is the use of attributes & automation parameters (both formerly known as “keys”). In fact, it’s unlikely you’ll ever build an Automation without using these components, but what exactly are they?
Attributes & automation parameters enable the automation author to pass data values from one automation component to the next. During this webinar, our FME Flow Specialists will cover leveraging the three types of these output attributes & parameters in FME Flow: Event, Custom, and Automation. As a bonus, they’ll also be making use of the Split-Merge Block functionality.
You’ll leave this webinar with a better understanding of how to maximize the potential of automations by making use of attributes & automation parameters, with the ultimate goal of setting your enterprise integration workflows up on autopilot.
How information systems are built or acquired puts information, which is what they should be about, in a secondary place. Our language adapted accordingly, and we no longer talk about information systems but applications. Applications evolved in a way to break data into diverse fragments, tightly coupled with applications and expensive to integrate. The result is technical debt, which is re-paid by taking even bigger "loans", resulting in an ever-increasing technical debt. Software engineering and procurement practices work in sync with market forces to maintain this trend. This talk demonstrates how natural this situation is. The question is: can something be done to reverse the trend?
AppSec PNW: Android and iOS Application Security with MobSFAjin Abraham
Mobile Security Framework - MobSF is a free and open source automated mobile application security testing environment designed to help security engineers, researchers, developers, and penetration testers to identify security vulnerabilities, malicious behaviours and privacy concerns in mobile applications using static and dynamic analysis. It supports all the popular mobile application binaries and source code formats built for Android and iOS devices. In addition to automated security assessment, it also offers an interactive testing environment to build and execute scenario based test/fuzz cases against the application.
This talk covers:
Using MobSF for static analysis of mobile applications.
Interactive dynamic security assessment of Android and iOS applications.
Solving Mobile app CTF challenges.
Reverse engineering and runtime analysis of Mobile malware.
How to shift left and integrate MobSF/mobsfscan SAST and DAST in your build pipeline.
"Choosing proper type of scaling", Olena SyrotaFwdays
Imagine an IoT processing system that is already quite mature and production-ready and for which client coverage is growing and scaling and performance aspects are life and death questions. The system has Redis, MongoDB, and stream processing based on ksqldb. In this talk, firstly, we will analyze scaling approaches and then select the proper ones for our system.
Fueling AI with Great Data with Airbyte WebinarZilliz
This talk will focus on how to collect data from a variety of sources, leveraging this data for RAG and other GenAI use cases, and finally charting your course to productionalization.
Have you ever been confused by the myriad of choices offered by AWS for hosting a website or an API?
Lambda, Elastic Beanstalk, Lightsail, Amplify, S3 (and more!) can each host websites + APIs. But which one should we choose?
Which one is cheapest? Which one is fastest? Which one will scale to meet our needs?
Join me in this session as we dive into each AWS hosting service to determine which one is best for your scenario and explain why!
"$10 thousand per minute of downtime: architecture, queues, streaming and fin...Fwdays
Direct losses from downtime in 1 minute = $5-$10 thousand dollars. Reputation is priceless.
As part of the talk, we will consider the architectural strategies necessary for the development of highly loaded fintech solutions. We will focus on using queues and streaming to efficiently work and manage large amounts of data in real-time and to minimize latency.
We will focus special attention on the architectural patterns used in the design of the fintech system, microservices and event-driven architecture, which ensure scalability, fault tolerance, and consistency of the entire system.
"Frontline Battles with DDoS: Best practices and Lessons Learned", Igor IvaniukFwdays
At this talk we will discuss DDoS protection tools and best practices, discuss network architectures and what AWS has to offer. Also, we will look into one of the largest DDoS attacks on Ukrainian infrastructure that happened in February 2022. We'll see, what techniques helped to keep the web resources available for Ukrainians and how AWS improved DDoS protection for all customers based on Ukraine experience
Northern Engraving | Modern Metal Trim, Nameplates and Appliance PanelsNorthern Engraving
What began over 115 years ago as a supplier of precision gauges to the automotive industry has evolved into being an industry leader in the manufacture of product branding, automotive cockpit trim and decorative appliance trim. Value-added services include in-house Design, Engineering, Program Management, Test Lab and Tool Shops.
How to Interpret Trends in the Kalyan Rajdhani Mix Chart.pdfChart Kalyan
A Mix Chart displays historical data of numbers in a graphical or tabular form. The Kalyan Rajdhani Mix Chart specifically shows the results of a sequence of numbers over different periods.
What is an RPA CoE? Session 1 – CoE VisionDianaGray10
In the first session, we will review the organization's vision and how this has an impact on the COE Structure.
Topics covered:
• The role of a steering committee
• How do the organization’s priorities determine CoE Structure?
Speaker:
Chris Bolin, Senior Intelligent Automation Architect Anika Systems
For the full video of this presentation, please visit: https://www.edge-ai-vision.com/2024/06/temporal-event-neural-networks-a-more-efficient-alternative-to-the-transformer-a-presentation-from-brainchip/
Chris Jones, Director of Product Management at BrainChip , presents the “Temporal Event Neural Networks: A More Efficient Alternative to the Transformer” tutorial at the May 2024 Embedded Vision Summit.
The expansion of AI services necessitates enhanced computational capabilities on edge devices. Temporal Event Neural Networks (TENNs), developed by BrainChip, represent a novel and highly efficient state-space network. TENNs demonstrate exceptional proficiency in handling multi-dimensional streaming data, facilitating advancements in object detection, action recognition, speech enhancement and language model/sequence generation. Through the utilization of polynomial-based continuous convolutions, TENNs streamline models, expedite training processes and significantly diminish memory requirements, achieving notable reductions of up to 50x in parameters and 5,000x in energy consumption compared to prevailing methodologies like transformers.
Integration with BrainChip’s Akida neuromorphic hardware IP further enhances TENNs’ capabilities, enabling the realization of highly capable, portable and passively cooled edge devices. This presentation delves into the technical innovations underlying TENNs, presents real-world benchmarks, and elucidates how this cutting-edge approach is positioned to revolutionize edge AI across diverse applications.
“Temporal Event Neural Networks: A More Efficient Alternative to the Transfor...
Data structures and algorithms
1. Abstract data type
A theoretical description of an algorithm, if realized in
application is affected very much by:
computer resources,
implementation,
data.
Such a theory include fundamental concepts:
Abstract Data Type (ADT) or data type, or data
structures
tools to express operations of algorithms;
computational resources to implement the algorithm
and test its functionality;
evaluation of the complexity of algorithms.
2. What is a Data Type?
A name for the INTEGER data type
E.g., “int”
Collection of (possible) data items
E.g., integers can have values in the range of -231 to 231 –
1
Associated set of operations on those data items
E.g., arithmetic operations like +, -, *, /, etc.
3. Abstract data type
An abstract data type (ADT) is defined as a
mathematical model of the data objects that make up a
data type, as well as the functions that operate on these
objects (and logical or other relations between objects).
ADT consist of two parts: data objects and operations with
data objects.
The term data type refers to the implementation of the
mathematical model specified by an ADT
The term data structure refers to a collection of computer
variables that are connected in some specific manner
The notion of data type include basic data types. Basic
data types are related to a programming language.
4. Example: Integer Set Data Type
ABSTRACT (Theoretical) DATA TYPE
Mathematical set of integers, I
Possible data items: -inf, …, -1, 0, 1, …, +inf
Operations: +, -, *, mod, div, etc.
Actual, Implemented Data Type (available in C++):
It’s called “int”
Only has range of -231 to 231 – 1 for the possible
data items (instead of –inf to +inf)
Has same arithmetic operations available
What’s the relationship/difference between the ADT
and the Actual, Implemented Data Type in C++?
The range of possible data items is different.
5. The THREE Essentials…
ABSTRACT (Theoretical) DATA TYPE
E.g., the mathematical class I in our example
Actual IMPLEMENTED DATA TYPE
What you have in C++; for example, “int” in our example
INSTANTIATED DATA TYPE – DATA STRUCTURE
E.g., x in int x = 5; (in our example)
Stores (or structures) the data item(s)
Can be a variable, array, object, etc.; holds the actual data
(e.g., a specific value)
ADT – Class
DECLARATION
(lib.h)
Class
DEFINITION
(lib.cpp)
Object
(project.cpp)
6. Implementation of an ADT
The data structures used in implementations are EITHER
already provided in a programming language (primitive or
built-in) or are built from the language constructs (user-
defined).
In either case, successful software design uses data
abstraction:
Separating the declaration of a data type from its
implementation.
7. Summary of ADT
(Abstract or Actual) Data Types have three properties:
Name
Possible Data Items
Operations on those data items
The Data Type declaration goes in the .h (header) file –
e.g., the class declaration
The Data Type definitions go in the .cpp
(implementation) file – e.g., the class definition
8. Stacks
Stacks are a special form of collection
with LIFO semantics
Two methods
int push( Stack s, void *item );
- add item to the top of the stack
void *pop( Stack s );
- remove an item from the top of the stack
Like a plate stacker
other methods
int IsEmpty( Stack s );
/* Return TRUE if empty */
void *Top( Stack s );
/* Return the item at the top,
without deleting it */
9. Stacks
This ADT covers a set of objects as well as operations performed on
these objects:
Initialize (S) – creates a necessary structured space in computer
memory to locate objects in S;
Push(x) – inserts x into S;
Pop – deletes object from the stack that was most recently
inserted into;
Top – returns an object from the stack that was most recently
inserted into;
Kill (S) - releases an amount of memory occupied by S.
The operations with stack objects obey LIFO property: Last-In-First-
Out. This is a logical constrain or logical condition. The operations
Initialize and Kill are more oriented to an implementation of this ADT,
but they are important in some algorithms and applications too. The
stack is a dynamic data set with a limited access to objects.
10. Stacks - Implementation
Arrays
Provide a stack capacity to the constructor
Flexibility limited but matches many real uses
Capacity limited by some constraint
Memory in your computer
Size of the plate stacker, etc
push, pop methods
Variants of AddToC…, DeleteFromC…
Linked list also possible
Stack:
basically a Collection with special semantics!
11. 11
Array Stack Implementation
We can use an array of elements as a stack
The top is the index of the next available element in the
array
top integer
Object of type T Object of type T nullT [ ] stack
12. 12
Linked Stack Implementation
We can use the same LinearNode class that we used for
LinkedSet implementation
We change the attribute name to “top” to have a
meaning consistent with a stack
Object of type T
top LinearNode next;
T element;
Object of type T
LinearNode next;
T element;
null
count integer
17. The N-Queens Problem
Two queens are not
allowed in the same row,
or in the same column, or
along the same diagonal.
18. The N-Queens Problem
The number of queens,
and the size of the board
can vary.
N Queens
N columns
19. The N-Queens Problem
We will write a program
which tries to find a way to
place N queens on an N x
N chess board.
20. How the program works
The program
uses a stack to
keep track of
where each
queen is placed.
21. How the program works
Each time the
program decides
to place a queen
on the board,
the position of the
new queen is
stored in a record
which is placed in
the stack.
ROW 1, COL
1
22. How the program works
We also have an
integer variable to
keep track of how
many rows have
been filled so far.
ROW 1, COL
1
1 filled
23. How the program works
Each time we try
to place a new
queen in the next
row, we start by
placing the queen
in the first
column...
ROW 1, COL
1
1 filled
ROW 2, COL
1
24. How the program works
...if there is a
conflict with
another queen,
then we shift the
new queen to the
next column.
ROW 1, COL
1
1 filled
ROW 2, COL
2
25. How the program works
If another conflict
occurs, the queen
is shifted
rightward again.
ROW 1, COL
1
1 filled
ROW 2, COL
3
26. How the program works
When there are
no conflicts, we
stop and add one
to the value of
filled.
ROW 1, COL
1
2 filled
ROW 2, COL
3
27. How the program works
Let's look at the
third row. The
first position we
try has a conflict...
ROW 1, COL
1
2 filled
ROW 2, COL
3
ROW 3, COL
1
28. How the program works
...so we shift to
column 2. But
another conflict
arises...
ROW 1, COL
1
2 filled
ROW 2, COL
3
ROW 3, COL
2
29. How the program works
...and we shift to
the third column.
Yet another
conflict arises...
ROW 1, COL
1
2 filled
ROW 2, COL
3
ROW 3, COL
3
30. How the program works
...and we shift to
column 4.
There's still a
conflict in column
4, so we try to
shift rightward
again...
ROW 1, COL
1
2 filled
ROW 2, COL
3
ROW 3, COL
4
31. How the program works
...but there's
nowhere else to
go.
ROW 1, COL
1
2 filled
ROW 2, COL
3
ROW 3, COL
4
32. How the program works
When we run out of
room in a row:
pop the stack,
reduce filled by 1
and continue
working on the
previous row.
ROW 1, COL
1
1 filled
ROW 2, COL
3
33. How the program works
Now we continue
working on row 2,
shifting the queen
to the right.
ROW 1, COL
1
1 filled
ROW 2, COL
4
34. How the program works
This position has
no conflicts, so
we can increase
filled by 1, and
move to row 3.
ROW 1, COL
1
2 filled
ROW 2, COL
4
35. How the program works
In row 3, we start
again at the first
column.
ROW 1, COL
1
2 filled
ROW 2, COL
4
ROW 3, COL
1
36. Pseudocode for N-Queens
Initialize a stack where we can keep track of
our decisions.
Place the first queen, pushing its position
onto the stack and setting filled to 0.
repeat these steps
if there are no conflicts with the queens...
else if there is a conflict and there is room to shift the
current queen rightward...
else if there is a conflict and there is no room to shift
the current queen rightward...
37. Pseudocode for N-Queens
repeat these steps
if there are no conflicts with the queens...
Increase filled by 1. If filled is now N,
then
the algorithm is done. Otherwise, move
to
the next row and place a queen in the
first column.
38. Pseudocode for N-Queens
repeat these steps
if there are no conflicts with the queens...
else if there is a conflict and there is room to shift the
current queen rightward...
Move the current queen rightward,
adjusting the record on top of the stack
to indicate the new position.
39. Pseudocode for N-Queens
repeat these steps
if there are no conflicts with the queens...
else if there is a conflict and there is room to shift the
current queen rightward...
else if there is a conflict and there is no room to shift
the current queen rightward...
Backtrack!
Keep popping the stack, and reducing filled
by 1, until you reach a row where the queen
can be shifted rightward. Shift this queen right.
40. Pseudocode for N-Queens
repeat these steps
if there are no conflicts with the queens...
else if there is a conflict and there is room to shift the
current queen rightward...
else if there is a conflict and there is no room to shift
the current queen rightward...
Backtrack!
Keep popping the stack, and reducing filled
by 1, until you reach a row where the queen
can be shifted rightward. Shift this queen right.
41. Stacks - Relevance
Stacks appear in computer programs
Key to call / return in functions & procedures
Stack frame allows recursive calls
Call: push stack frame
Return: pop stack frame
Stack frame
Function arguments
Return address
Local variables
42. Stacks have many applications.
The application which we have shown is called
backtracking.
The key to backtracking: Each choice is recorded in a
stack.
When you run out of choices for the current decision, you
pop the stack, and continue trying different choices for the
previous decision.
Summary
43. 43
Stacks and Queues
Array Stack Implementation
Linked Stack Implementation
Queue Abstract Data Type (ADT)
Queue ADT Interface
Queue Design Considerations
44. 44
Queue Abstract Data Type
A queue is a linear collection where the elements are
added to one end and removed from the other end
The processing is first in, first out (FIFO)
The first element put on the queue is the first element
removed from the queue
Think of a line of people waiting for a bus (The British call
that “queuing up”)
45. 45
A Conceptual View of a Queue
Rear of Queue
(or Tail)
Adding an Element Removing an Element
Front of Queue
(or Head)
46. 46
Queue Terminology
We enqueue an element on a queue to add one
We dequeue an element off a queue to remove one
We can also examine the first element without removing
it
We can determine if a queue is empty or not and how
many elements it contains (its size)
The L&C QueueADT interface supports the above
operations and some typical class operations such as
toString()
47. 47
Queue Design Considerations
Although a queue can be empty, there is no concept for it
being full. An implementation must be designed to manage
storage space
For first and dequeue operation on an empty queue,
this implementation will throw an exception
Other implementations could return a value null that is
equivalent to “nothing to return”
48. 48
Queue Design Considerations
No iterator method is provided
That would be inconsistent with restricting access to the
first element of the queue
If we need an iterator or other mechanism to access the
elements in the middle or at the end of the collection,
then a queue is not the appropriate data structure to use
49. Queues
This ADT covers a set of objects as well as operations performed on objects:
queueinit (Q) – creates a necessary structured space in computer memory to
locate objects in Q;
put (x) – inserts x into Q;
get – deletes object from the queue that has been residing in Q the
longest;
head – returns an object from the queue that has been residing in Q the
longest;
kill (Q) – releases an amount of memory occupied by Q.
The operations with queue obey FIFO property: First-In-First-Out. This is a
logical constrain or logical condition. The queue is a dynamic data set with a
limited access to objects. The application to illustrate usage of a queue is:
queueing system simulation (system with waiting lines)
(implemented by using the built-in type of pointer)
50. Queue implementation
Just as with stacks, queues can be implemented using arrays or lists.
For the first of all, let’s consider the implementation using arrays.
Define an array for storing the queue elements, and two markers:
one pointing to the location of the head of the queue,
the other to the first empty space following the tail.
When an item is to be added to the queue, a test to see if the tail
marker points to a valid location is made, then the item is added to
the queue and the tail marker is incremented by 1. When an item is to
be removed from the queue, a test is made to see if the queue is
empty and, if not, the item at the location pointed to by the head
marker is retrieved and the head marker is incremented by 1.
51. Queue implementation
This procedure works well until the first time
when the tail marker reaches the end of the
array. If some removals have occurred during
this time, there will be empty space at the
beginning of the array. However, because the
tail marker points to the end of the array, the
queue is thought to be 'full' and no more data
can be added.
We could shift the data so that the head of the
queue returns to the beginning of the array
each time this happens, but shifting data is
costly in terms of computer time, especially if
the data being stored in the array consist of
large data objects.
52. Queue implementation
We may now formalize the algorithms for dealing
with queues in a circular array.
• Creating an empty queue: Set Head = Tail = 0.
• Testing if a queue is empty: is Head == Tail?
• Testing if a queue is full: is (Tail + 1) mod QSIZE
== Head?
• Adding an item to a queue: if queue is not full, add
item at location Tail and set Tail = (Tail +
1) mod QSIZE.
• Removing an item from a queue: if queue is not
empty, remove item from location Head and
set Head = (Head + 1) mod QSIZE.
53. Linked list
kes it possible to access any element in the data structure in constant time.
ss of the data structure in memory, we can find the address of any element
simply calculating its offset from the starting address.
of a sequentially mapped data structure:
me amount of time to access any element, a sequentially-mapped data
random access data structure. That is, the accessing time is independent
ructure, and therefore requires O(l) time.
esentations of (a) a singly-linked list and (b) a doubly-linked list:
ray is an example of a sequentially mapped data structure:
use it takes the same amount of time to access any element, a sequentially-mapped da
ure is also called a random access data structure. That is, the accessing time is independe
size of the data structure, and therefore requires O(l) time.
Schematic representations of (a) a singly-linked list and (b) a doubly-linked list:
Reset, and Next operations modify the lists to which they are
imply query lists in order to obtain information about them.
Sequential Mapping
ise a given data structure are stored one after the other in
we say that the data structure is sequentially mapped into
ble to access any element in the data structure in constant time.
ta structure in memory, we can find the address of any element
ulating its offset from the starting address.
tially mapped data structure:
55. Linked list
The List ADT
A list is one of the most fundamental data structures
used to store a collection of data items.
The importance of the List ADT is that it can be used
to implement a wide variety of other ADTs. That is, the
LIST ADT often serves as a basic building block in the
construction of more complicated ADTs.
A list may be defined as a dynamic ordered n-tuple:
L == (l1, 12, ....., ln)
56. Linked list
The use of the term dynamic in this definition is
meant to emphasize that the elements in this
n-tuple may change over time.
Notice that these elements have a linear order that is
based upon their position in the list. The first element
in the list, 11, is called the head of the list.
The last element, ln, is referred to as the tail of the
list.
The number of elements in a list L is refered to as the
length of the list.
Thus the empty list, represented by (), has length 0. A
list can homogeneous or heterogeneous.
57. Linked list
0. Initialize ( L ). This operation is needed to allocate the
amount of memory and to give a structure to this amount.
1. Insert (L, x, i). If this operation is successful, the
boolean value true is returned; otherwise, the boolean
value false is returned.
2. Append (L, x). Adds element x to the tail of L, causing
the length of the list to become n+1. If this operation is
successful, the boolean value true is returned; otherwise,
the boolean value false is returned.
3. Retrieve (L, i). Returns the element stored at position i
of L, or the null value if position i does not exist.
4. Delete (L, i). Deletes the element stored at position i of
L, causing elements to move in their positions.
5. Length (L). Returns the length of L.
58. Linked list
6. Reset (L). Resets the current position in L to the
head (i.e., to position 1) and returns the value 1. If the
list is empty, the value 0 is returned.
7. Current (L). Returns the current position in L.
8. Next (L). Increments and returns the current
position in L.
Note that only the Insert, Delete, Reset, and Next
operations modify the lists to which they are applied.
The remaining operations simply query lists in order to
obtain information about them.
59. Linked lists
Flexible space use
Dynamically allocate space for each element as
needed
Include a pointer to the next item
ç Linked list
Each node of the list contains
the data item (an object pointer in our ADT)
a pointer to the next node
Data Next
object
60. Linked lists
Collection structure has a pointer to the list head
Initially NULL
Add first item
Allocate space for node
Set its data pointer to object
Set Next to NULL
Set Head to point to new node
Data Next
object
Head
Collection
node
61. Linked lists
Add second item
Allocate space for node
Set its data pointer to object
Set Next to current Head
Set Head to point to new node
Data Next
object
Head
Collection
node
Data Next
object2
node
64. Linked lists
Add time
Constant - independent of n
Search time
Worst case - n
Data Next
object
Head
Collection
node
Data Next
object2
node
65. Linked lists – Delete
Implementation
void *DeleteFromCollection( Collection c, void *key ) {
Node n, prev;
n = prev = c->head;
while ( n != NULL ) {
if ( KeyCmp( ItemKey( n->item ), key ) == 0 ) {
prev->next = n->next;
return n;
}
prev = n;
n = n->next;
}
return NULL;
}
head
66. Linked lists – Delete
Implementation
void *DeleteFromCollection( Collection c, void *key ) {
Node n, prev;
n = prev = c->head;
while ( n != NULL ) {
if ( KeyCmp( ItemKey( n->item ), key ) == 0 ) {
prev->next = n->next;
return n;
}
prev = n;
n = n->next;
}
return NULL;
}
head
Minor addition needed to allow
for deleting this one! An exercise!
67. Linked lists - LIFO and FIFO
Simplest implementation
Add to head
ç Last-In-First-Out (LIFO) semantics
Modifications
First-In-First-Out (FIFO)
Keep a tail pointer
struct t_node {
void *item;
struct t_node *next;
} node;
typedef struct t_node *Node;
struct collection {
Node head, tail;
};
tail is set in
the AddToCollection
method if
head == NULL
head
tail
68. Dynamic set ADT
The concept of a set serves as the basis for a wide variety of useful
abstract data types. A large number of computer applications involve
the manipulation of sets of data elements. Thus, it makes sense to
investigate data structures and algorithms that support efficient
implementation of various operations on sets.
Another important difference between the mathematical concept of a
set and the sets considered in computer science:
• a set in mathematics is unchanging, while the sets in CS are
considered to change over time as data elements are added or
deleted.
Thus, sets are refered here as dynamic sets. In addition, we will
assume that each element in a dynamic set contains an identifying
field called a key, and that a total ordering relationship exists on
these keys.
It will be assumed that no two elements of a dynamic set contain the
same key.
69. Dynamic set ADT
The concept of a dynamic set as an DYNAMIC SET ADT is to
be specified, that is, as a collection of data elements, along with
the legal operations defined on these data elements.
If the DYNAMIC SET ADT is implemented properly, application
programmers will be able to use dynamic sets without having to
understand their implementation details. The use of ADTs in this
manner simplifies design and development, and promotes
reusability of software components.
A list of general operations for the DYNAMIC SET ADT. In each
of these operations, S represents a specific dynamic set:
70. Dynamic set ADT
Search(S, k). Returns the element with key k in S, or the null value if an element
with key k is not in S.
Insert(S, x). Adds element x to S. If this operation is successful, the boolean value
true is returned; otherwise, the boolean value false is returned.
Delete(S, k). Removes the element with key k in S. If this operation is successful,
the boolean value true is returned; otherwise, the boolean value false is returned.
Minimum(S). Returns the element in dynamic set S that has the smallest key value,
or the null value if S is empty.
Maximum(S). Returns the element in S that has the largest key value, or the null
value if S is empty.
Predecessor(S, k). Returns the element in S that has the largest key value less
than k, or the null value if no such element exists.
Successor(S, k). Returns the element in S that has the smallest key value greater
than k, or the null value if no such element exists.
71. Dynamic set ADT
In many instances an application will only require the use of a few
DYNAMIC SET operations. Some groups of these operations are
used so frequently that they are given special names:
the ADT that supports Search, Insert, and Delete operations is called
the DICTIONARY ADT; the STACK, QUEUE, and PRIORITY QUEUE
ADTs are all special types of dynamic sets.
A variety of data structures will be described in forthcoming
considerations that they can be used to implement either the
DYNAMIC SET ADT, or ADTs that support specific subsets of the
DYNAMIC SET ADT operations.
Each of the data structures described will be analyzed in order to
determine how efficiently they support the implementation of these
operations. In each case, the analysis will be performed in terms of
n, the number of data elements stored in the dynamic set.
72. Generalized queue
Stacks and FIFO queues are identifying items according to the time that
they were inserted into the queue. Alternatively, the abstract concepts may
be identified in terms of a sequential listing of the items in order, and refer
to the basic operations of inserting and deleting items from the beginning
and the end of the list:
if we insert at the end and delete at the end, we get a stack
(precisely as in array implementation);
if we insert at the beginning and delete at the beginning, we also
get a stack (precisely as in linked-list implementation);
if we insert at the end and delete at the beginning, we get a
FIFO queue (precisely as in linked-list implementation);
if we insert at the beginning and delete at the end, we also get a
FIFO queue (this option does not correspond to any of
implementations given).
73. Generalized queue
Specifically, pushdown stacks and FIFO queues are special
instances of a more general ADT: the generalized queue. Instances
generalized queues differ in only the rule used when items are
removed:
for stacks, the rule is "remove the item that was most recently
inserted";
for FIFO queues, the rule is "remove the item that was least
recently inserted";
there are many other possibilities to consider.
A powerful alternative is the random queue, which uses the rule:
"remove a random item"
74. Generalized queue
The algorithm can expect to get any of the items on the
queue with equal probability. The operations of a random
queue can be implemented:
in constant time using an array representation (it requires
to reserve space ahead of time)
using linked-list alternative (which is less attractive
however, because implementing both, insertion and
deletion efficiently is a challenging task)
Random queues can be used as the basis for randomized
algorithms, to avoid, with high probability, worst-case
performance scenarios.
75. Generalized queue
Building on this point of view, the dequeue ADT may be
defined, where either insertion or deletion at either end are
allowed. The implementation of dequeue is a good exercise to
program.
The priority queue ADT is another example of generalized
queue. The items in a priority queue have keys and the rule for
deletion is: "remove the item with the smallest key"
The priority queue ADT is useful in a variety of applications,
and the problem of finding efficient implementations for this
ADT has been a research goal in computer science for many
years.
76. Heaps and the heapsort
Heaps and priority queues
Heap structure and position numbering
Heap structure property
Heap ordering property
Removal of top priority node
Inserting a new node into the heap
The heap sort
Source code for heap sort program
77. Heaps and priority queues
A heap is a data structure used to implement an efficient priority
queue. The idea is to make it efficient to extract the element with
the highest priority the next item in the queue to be processed.
We could use a sorted linked list, with O(1) operations to remove
the highest priority node and O(N) to insert a node. Using a tree
structure will involve both operations being O(log2N) which is
faster.
78. Heap structure and position numbering 1
A heap can be visualised as a binary tree in which every layer
is filled from the left. For every layer to be full, the tree would
have to have a size exactly equal to 2n1, e.g. a value for size in
the series 1, 3, 7, 15, 31, 63, 127, 255 etc.
So to be practical enough to allow for any particular size, a
heap has every layer filled except for the bottom layer which is
filled from the left.
80. Heap structure and position numbering 3
In the above diagram nodes are labelled based on position, and
not their contents. Also note that the left child of each node is
numbered node*2 and the right child is numbered node*2+1. The
parent of every node is obtained using integer division (throwing
away the remainder) so that for a node i's parent has position i/2 .
Because this numbering system makes it very easy to move
between nodes and their children or parents, a heap is commonly
implemented as an array with element 0 unused.
81. Heap Properties
A heap T storing n keys has height h = log(n + 1),
which is O(log n)
4
6
207
811
5
9
1214
15
2516
88. Removal of top priority node
The rest of these notes assume a min heap will be used.
Removal of the top node creates a hole at the top which is
"bubbled" downwards by moving values below it upwards,
until the hole is in a position where it can be replaced with
the rightmost node from the bottom layer. This process
restores the heap ordering property.
94. The heap sort
Using a heap to sort data involves performing N insertions
followed by N delete min operations as described above.
Memory usage will depend upon whether the data already
exists in memory or whether the data is on disk. Allocating the
array to be used to store the heap will be more efficient if N,
the number of records, can be known in advance. Dynamic
allocation of the array will then be possible, and this is likely
to be preferable to preallocating the array.
95. Heaps
A heap is a binary tree T that stores a key-element pairs at its
internal nodes
It satisfies two properties:
MinHeap: key(parent) key(child)
[OR MaxHeap: key(parent) ≥ key(child)]
all levels are full, except
the last one, which is
left-filled
4
6
207
811
5
9
1214
15
2516
96. What are Heaps Useful for?
To implement priority queues
Priority queue = a queue where all elements have a
“priority” associated with them
Remove in a priority queue removes the element with
the smallest priority
insert
removeMin
98. ADT for Min Heap
objects: n > 0 elements organized in a binary tree so that the value in each
node is at least as large as those in its children
method:
Heap Create(MAX_SIZE)::= create an empty heap that can
hold a maximum of max_size elements
Boolean HeapFull(heap, n)::= if (n==max_size) return TRUE
else return FALSE
Heap Insert(heap, item, n)::= if (!HeapFull(heap,n)) insert
item into heap and return the resulting heap
else return error
Boolean HeapEmpty(heap, n)::= if (n>0) return FALSE
else return TRUE
Element Delete(heap,n)::= if (!HeapEmpty(heap,n)) return one
instance of the smallest element in the heap
and remove it from the heap
else return error
99. Building a Heap
build (n + 1)/2 trivial
one-element heaps
build three-element
heaps on top of them