This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It covers various abstract data types including arrays, polynomials, sparse matrices, and strings. It provides examples of implementing one-dimensional and multi-dimensional arrays in C. Structures and unions are described as a way to group heterogeneous data. Self-referential structures and implementation of abstract data types using arrays are also discussed.
Arrays are data structures that store a collection of data values of the same type in consecutive memory locations that can be individually referenced by their numeric index. Different representations of arrays are possible including using a single block of memory or a collection of elements. Common operations on arrays include retrieving or storing elements by their index and traversing the entire array sequentially.
Computers use their memory for storing instructions of the programs and the values of the variables. Memory is a sequential collection of storage cells. Each cell has an address associated with it. Whenever we declare a variable, the system allocates, somewhere in the memory, a memory location and a unique address is assigned to this location.c pointers lecture
This document discusses data structures in C, specifically lists and pointers. It covers linked lists as an alternative to arrays for representing lists, with each node containing a data element and pointer to the next node. It describes using pointers in C with address and dereference operators. It also covers dynamically allocating memory with malloc and free. The document discusses implementing singly linked lists, stacks, and queues using pointers. It covers representing polynomials as linked lists and operations like adding and erasing polynomials.
This document discusses arrays and structures. It begins by defining an array as a set of index-value pairs where each index maps to a value. Arrays are commonly implemented using consecutive memory locations. Structures group related data and allow accessing members via dot notation. The document provides examples of one-dimensional arrays in C and comparing integer pointers to arrays. It also covers self-referential structures, ordered lists, polynomials represented as terms, and sparse matrices stored as row-column-value triples. Functions for each abstract data type are defined, such as adding and multiplying polynomials or transposing a sparse matrix.
This document summarizes arrays and structures in C including:
1) Arrays are sets of index-value pairs that use consecutive memory locations. Structures group related data and can reference themselves.
2) C implements 1D arrays using consecutive memory locations accessed via indexes. Structures allow defining custom data types.
3) Operations on ordered lists include retrieving, inserting, deleting elements. Polynomials are represented as ordered pairs of exponents and coefficients. Addition involves comparing exponents and combining coefficients.
Use the following data set that compares age to average years lef.docxdickonsondorris
Use the following data set that compares age to average "years left to live" to answer the following questions.
Age 10 20 30 40 50 60 70 80 90 100
Years to live 59.2 49.6 40.7 31.9 24.0 17.2 11.6 7.2 4 .4 2.8
a) Show the scatterplot for this data with the least squares regression line. Find R^2. How much of the variation is explained by the regression line?
b) Experiment with the non-linear regressions available on the calculator. Which seem to fit? Show the scatterplot with three different regression curves from the calculator. Label each equation, as well as the applicable R^2.
c) Choose a regression equation to predict how many "years left" a person has if he is now 101 years old. Can he count on celebrating Christmas 2015?
InfoTest.javaInfoTest.javapackage assignment1;
importstatic org.junit.Assert.*;
import org.junit.Test;
publicclassInfoTest{
@Test
publicvoid testInfo(){
Info tempInfo =newInfo();
assertNotNull(tempInfo.tmp);
}
@Test
publicvoid testInsert(){
Info tempInfo =newInfo();
// Insert into an empty list
tempInfo.insert(30);
assertEquals(30, tempInfo.get(0));
// Insert an item to be placed at the beginning of the list
tempInfo.insert(4);
assertEquals(4, tempInfo.get(0));
assertEquals(30, tempInfo.get(1));
// Insert an item to be placed at the end of the list
tempInfo.insert(20);
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
// Insert an which already exists
tempInfo.insert(20);
assertEquals(4, tempInfo.get(0));
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
}
@Test
publicvoid testDelete(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// delete from the middle
tempInfo.delete(10);
assertEquals(5, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the beginning
tempInfo.insert(10);
tempInfo.delete(5);
assertEquals(10, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the end
tempInfo.insert(5);
tempInfo.delete(15);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
// delete something that does not exist
tempInfo.insert(15);
tempInfo.delete(7);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(1));
}
@Test
publicvoid testGet(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// get items at the beginning, middle, and end of the list
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(2));
// get an unexisting item
assertNull(tempInfo.get(3));
}
@Test
publicvoid testCount(){
Info tempInfo =newInfo();
/ ...
This document provides a summary of the main data types in Python including text, numeric, sequence, mapping, set, boolean, and binary types. It discusses the main characteristics of integers, floats, complexes, strings, lists, tuples, dictionaries, and sets. It covers how to define, access, modify, loop through and add/remove items for each data type. The key details covered include slicing strings, converting between types, appending/inserting/removing list items, immutable tuples, unordered sets and indexed dictionaries.
Arrays are data structures that store a collection of data values of the same type in consecutive memory locations that can be individually referenced by their numeric index. Different representations of arrays are possible including using a single block of memory or a collection of elements. Common operations on arrays include retrieving or storing elements by their index and traversing the entire array sequentially.
Computers use their memory for storing instructions of the programs and the values of the variables. Memory is a sequential collection of storage cells. Each cell has an address associated with it. Whenever we declare a variable, the system allocates, somewhere in the memory, a memory location and a unique address is assigned to this location.c pointers lecture
This document discusses data structures in C, specifically lists and pointers. It covers linked lists as an alternative to arrays for representing lists, with each node containing a data element and pointer to the next node. It describes using pointers in C with address and dereference operators. It also covers dynamically allocating memory with malloc and free. The document discusses implementing singly linked lists, stacks, and queues using pointers. It covers representing polynomials as linked lists and operations like adding and erasing polynomials.
This document discusses arrays and structures. It begins by defining an array as a set of index-value pairs where each index maps to a value. Arrays are commonly implemented using consecutive memory locations. Structures group related data and allow accessing members via dot notation. The document provides examples of one-dimensional arrays in C and comparing integer pointers to arrays. It also covers self-referential structures, ordered lists, polynomials represented as terms, and sparse matrices stored as row-column-value triples. Functions for each abstract data type are defined, such as adding and multiplying polynomials or transposing a sparse matrix.
This document summarizes arrays and structures in C including:
1) Arrays are sets of index-value pairs that use consecutive memory locations. Structures group related data and can reference themselves.
2) C implements 1D arrays using consecutive memory locations accessed via indexes. Structures allow defining custom data types.
3) Operations on ordered lists include retrieving, inserting, deleting elements. Polynomials are represented as ordered pairs of exponents and coefficients. Addition involves comparing exponents and combining coefficients.
Use the following data set that compares age to average years lef.docxdickonsondorris
Use the following data set that compares age to average "years left to live" to answer the following questions.
Age 10 20 30 40 50 60 70 80 90 100
Years to live 59.2 49.6 40.7 31.9 24.0 17.2 11.6 7.2 4 .4 2.8
a) Show the scatterplot for this data with the least squares regression line. Find R^2. How much of the variation is explained by the regression line?
b) Experiment with the non-linear regressions available on the calculator. Which seem to fit? Show the scatterplot with three different regression curves from the calculator. Label each equation, as well as the applicable R^2.
c) Choose a regression equation to predict how many "years left" a person has if he is now 101 years old. Can he count on celebrating Christmas 2015?
InfoTest.javaInfoTest.javapackage assignment1;
importstatic org.junit.Assert.*;
import org.junit.Test;
publicclassInfoTest{
@Test
publicvoid testInfo(){
Info tempInfo =newInfo();
assertNotNull(tempInfo.tmp);
}
@Test
publicvoid testInsert(){
Info tempInfo =newInfo();
// Insert into an empty list
tempInfo.insert(30);
assertEquals(30, tempInfo.get(0));
// Insert an item to be placed at the beginning of the list
tempInfo.insert(4);
assertEquals(4, tempInfo.get(0));
assertEquals(30, tempInfo.get(1));
// Insert an item to be placed at the end of the list
tempInfo.insert(20);
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
// Insert an which already exists
tempInfo.insert(20);
assertEquals(4, tempInfo.get(0));
assertEquals(20, tempInfo.get(1));
assertEquals(30, tempInfo.get(2));
}
@Test
publicvoid testDelete(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// delete from the middle
tempInfo.delete(10);
assertEquals(5, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the beginning
tempInfo.insert(10);
tempInfo.delete(5);
assertEquals(10, tempInfo.get(0));
assertEquals(15, tempInfo.get(1));
// delete from the end
tempInfo.insert(5);
tempInfo.delete(15);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
// delete something that does not exist
tempInfo.insert(15);
tempInfo.delete(7);
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(1));
}
@Test
publicvoid testGet(){
Info tempInfo =newInfo();
tempInfo.insert(15);
tempInfo.insert(5);
tempInfo.insert(10);
// get items at the beginning, middle, and end of the list
assertEquals(5, tempInfo.get(0));
assertEquals(10, tempInfo.get(1));
assertEquals(15, tempInfo.get(2));
// get an unexisting item
assertNull(tempInfo.get(3));
}
@Test
publicvoid testCount(){
Info tempInfo =newInfo();
/ ...
This document provides a summary of the main data types in Python including text, numeric, sequence, mapping, set, boolean, and binary types. It discusses the main characteristics of integers, floats, complexes, strings, lists, tuples, dictionaries, and sets. It covers how to define, access, modify, loop through and add/remove items for each data type. The key details covered include slicing strings, converting between types, appending/inserting/removing list items, immutable tuples, unordered sets and indexed dictionaries.
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
Arrays are data structures that store a collection of data elements of the same type using a single variable name to represent the entire collection. Structures group together data of different types under one name. Sparse matrices represent matrices with many zero elements by only storing the non-zero elements, using triples of row, column, and value to represent each non-zero term. Transposing a sparse matrix involves taking each non-zero term <i,j,value> and storing it as <j,i,value> in the transpose.
The document discusses various data structures for implementing lists, including array-based and pointer-based implementations. It describes list operations like insert, find, and delete. For pointer-based lists, it covers issues like using a header node, doubly linked lists, and circularly linked lists. The document also discusses implementing polynomials as linked lists sorted by exponent and sorting algorithms like bucket sort and radix sort.
An array is a collection of similar elements that are stored in contiguous memory locations. Arrays in C can have one or more dimensions. One-dimensional arrays are declared with the type of elements, name of the array, and number of elements within brackets (e.g. int marks[30]). Multi-dimensional arrays represent matrices and are declared with the number of rows and columns (e.g. int arr[5][10]). Individual elements within an array are accessed via indices (e.g. arr[2][7]). Pointers in C are related to arrays - the name of an array represents the address of its first element, and pointer arithmetic can be used to access successive elements in an array.
The document provides an overview of common topics that confuse new C programmers, including control structures, variable types, pointers, arrays, structs, linked lists, and recursion. It discusses each concept in 1-3 paragraphs, explaining what they are and providing basic examples. It also covers debugging strategies such as printing variables, reducing complexity, and inserting early returns to isolate issues.
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
Need done for Date Structures please!
4.18 LAB: Sorted number list implementation with linked lists
Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables:
a double data value,
a pointer to the next node, and
a pointer to the previous node.
Each member variable is protected. So code outside of the class must use the provided getter and
setter member functions to get or set a member variable.
Node.h is read only, since no changes are required.
Step 2: Implement the Insert() member function
A class for a sorted, doubly-linked list is declared in SortedNumberList.h. Implement the
SortedNumberList class's Insert() member function. The function must create a new node with
the parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node
with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the Remove() member function
Implement the SortedNumberList class's Remove() member function. The function takes a
parameter for the number to be removed from the list. If the number does not exist in the list, the
list is not changed and false is returned. Otherwise, the first instance of the number is removed
from the list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
#include "SortedNumberList.h"
using namespace std;
void PrintList(SortedNumberList& list);
vector<string> SpaceSplit(string source);
int main(int argc, char *argv[]) {
// Read the line of input numbers
string inputLine;
getline(cin, inputLine);
// Split on space character
vector<string> terms = SpaceSplit(inputLine);
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list;
for (auto term : terms) {
double number = stod(term);
cout << "List after inserting " << number << ": " << endl;
list.Insert(number);
PrintList(list);
}
/*
// Read the input line with numbers to remove
getline(cin, inputLine);
terms = SpaceSplit(inputLine);
// Remove each value
for (auto term : terms) {
double number = stod(term);
cout << "List after removing " << number << ": " << endl;
list.Remove(number.
Arrays allow the storage and manipulation of multiple values of the same type. An array stores elements of the same type in a contiguous block of memory with indexes to access each element. One-dimensional arrays are declared with a size and accessed using indexes. Two-dimensional arrays represent tabular data and are accessed using row and column indexes. Arrays of objects allow storing and accessing multiple objects, and their elements can be accessed and manipulated similarly to primitive arrays.
C programming language allows for the declaration of arrays, which can store a fixed number of elements of the same data type. Arrays provide an efficient way to store and access related data sequentially in memory. Individual elements in an array are accessed via an index, and multi-dimensional arrays can model tables of data with multiple indices to access each element.
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
Arrays, stacks, queues, and linked lists are common data structures in computer science. Arrays allow direct access to elements but have fixed size, while linked lists can dynamically grow and shrink but require traversing nodes sequentially. Stacks follow LIFO (last in first out) and queues follow FIFO (first in first out) ordering for inserting and removing elements. Linked lists store data in nodes that link to the next node, allowing efficient insertion/removal anywhere in the list. Common operations on these structures include push/pop for stacks, enqueue/dequeue for queues, and insert/delete nodes for linked lists.
The document discusses representing sparse matrices using linked lists. Sparse matrices have mostly zero values, so they are more efficiently represented by only storing the non-zero elements and their indices rather than all elements. This can save memory and computing time. The document provides examples of representing a sparse matrix using arrays or linked lists, with the linked list approach storing each non-zero element as a node with fields for row, column, value, and a pointer to the next node.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
This document provides an overview of key Python concepts including numbers, strings, variables, lists, tuples, dictionaries, and sets. It defines each concept and provides examples. Numbers discusses integer, float, and complex data types. Strings covers string operations like accessing characters, concatenation, formatting and methods. Variables explains variable naming rules and scopes. Lists demonstrates accessing, modifying, and sorting list elements. Tuples describes immutable ordered collections. Dictionaries defines storing and accessing data via keys and values. Sets introduces unordered unique element collections.
Pointer variables contain memory addresses that point to other variables in memory. A pointer contains the address of another variable. Pointers provide indirect access to data in memory. Pointer variables must be declared with a data type and the * symbol indicates it is a pointer. The & operator returns the memory address of a variable and * dereferences a pointer to access the value at that memory address. Pointers can be assigned, compared, and perform arithmetic operations like incrementing to point to the next memory location.
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
Pointer is a variable in C++ that holds the address of another variable. Pointers allow accessing the memory location of other variables. There are different types of pointers based on the data type they are pointing to such as integer, character, class etc. Pointers are declared using an asterisk * before the pointer variable name. The address of a variable can be assigned to a pointer using the & address of operator. Pointers can be used to access members of a class and pass arrays to functions. The this pointer represents the address of the object inside member functions. Virtual functions allow dynamic binding at runtime in inheritance.
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
The document discusses arrays and array data structures. It defines an array as a set of index-value pairs where each index maps to a single value. It then describes the common array abstract data type (ADT) with methods like create, retrieve, and store for manipulating arrays. The document also discusses sparse matrix data structures and provides an ADT for sparse matrices with methods like create, transpose, add, and multiply.
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
The document discusses the concepts of SAP-1 (Simple Assembly Processor 1), a simple computer designed for educational purposes. It describes the components of SAP-1 including the program counter, memory, instruction register, accumulator, controller, and their functions. The timing diagrams for the fetch cycle are explained in detail over three states - address state, increment state, and memory state. The document also lists the instruction set of SAP-1 and provides an example program to demonstrate how it works.
Biological neurons and artificial neurons (ANN) both perform tasks like pattern recognition, learning, and generalization. ANNs are algorithmic models of biological neural systems and are composed of interconnected artificial neurons (nodes). ANNs can be trained with supervised, unsupervised, or reinforcement learning. They have applications in tasks like classification, pattern matching, and time series prediction.
(Parent reference for BST) Redefine TreeNode by adding a reference to.pdfarihantelehyb
(Parent reference for BST) Redefine TreeNode by adding a reference to a node\'s parent, as
shown below\': Reimplement the insert and delete methods in the BST class to update the parent
for each node in the tree. Add the following new method in BST:/** Returns the node for the
specified element. * Returns null if the element is not in the tree. */private TreeNode getNode(E
element)/** Returns true if the node for the element is a leaf */private boolean isLeaf(E
element)/** Returns the path of elements from the specified element * to the root in an array
list. */public ArrayList getPath(E e) Write a test program that prompts the user to enter 10
integers, adds them to the tree, deletes the first integer from the tree, and displays the paths for
all leaf nodes. Here is a sample run:
Solution
#include
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, r);
swap((a+l), (a+i)); //backtrack
}
}
}
int main()
{
char str[] = \"ABC\";
int n = strlen(str);
permute(str, 0, n-1);
return 0;
}
part ii radix sort:
c++
#include
using namespace std;
int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return main()
void countSort(int arr[], int n, int exp
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
adixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
void print(int arr[], int n)
{
for (int i = 0; i < n; i++)
cout << arr[i] << \" \";
}
int main()
{
int arr[] = {170, 45, 75, 90, 802, 24, 2, 66};
int n = sizeof(arr)/sizeof(arr[0]);
radixsort(arr, n);
print(arr, n);
return 0;
}
java:
import java.io.*;
import java.util.*;
class Radix {
static int getMax(int arr[], int n)
{
int mx = arr[0];
for (int i = 1; i < n; i++)
if (arr[i] > mx)
mx = arr[i];
return mx;
}
static void countSort(int arr[], int n, int exp)
{
int output[] = new int[n]; // output array
int i;
int count[] = new int[10];
Arrays.fill(count,0);
for (i = 0; i < n; i++)
count[ (arr[i]/exp)%10 ]++;
for (i = 1; i < 10; i++)
count[i] += count[i - 1];
for (i = n - 1; i >= 0; i--)
{
output[count[ (arr[i]/exp)%10 ] - 1] = arr[i];
count[ (arr[i]/exp)%10 ]--;
}
for (i = 0; i < n; i++)
arr[i] = output[i];
}
static void radixsort(int arr[], int n)
{
int m = getMax(arr, n);
for (int exp = 1; m/exp > 0; exp *= 10)
countSort(arr, n, exp);
}
static void print(int arr[], int n)
{
for (int i=0; i
#include
void swap(char *x, char *y)
{
char temp;
temp = *x;
*x = *y;
*y = temp;
void permute(char *a, int l, int r)
{
int i;
if (l == r)
printf(\"%s\ \", a);
else
{
for (i = l; i <= r; i++)
{
swap((a+l), (a+i));
permute(a, l+1, .
Arrays are data structures that store a collection of data elements of the same type using a single variable name to represent the entire collection. Structures group together data of different types under one name. Sparse matrices represent matrices with many zero elements by only storing the non-zero elements, using triples of row, column, and value to represent each non-zero term. Transposing a sparse matrix involves taking each non-zero term <i,j,value> and storing it as <j,i,value> in the transpose.
The document discusses various data structures for implementing lists, including array-based and pointer-based implementations. It describes list operations like insert, find, and delete. For pointer-based lists, it covers issues like using a header node, doubly linked lists, and circularly linked lists. The document also discusses implementing polynomials as linked lists sorted by exponent and sorting algorithms like bucket sort and radix sort.
An array is a collection of similar elements that are stored in contiguous memory locations. Arrays in C can have one or more dimensions. One-dimensional arrays are declared with the type of elements, name of the array, and number of elements within brackets (e.g. int marks[30]). Multi-dimensional arrays represent matrices and are declared with the number of rows and columns (e.g. int arr[5][10]). Individual elements within an array are accessed via indices (e.g. arr[2][7]). Pointers in C are related to arrays - the name of an array represents the address of its first element, and pointer arithmetic can be used to access successive elements in an array.
The document provides an overview of common topics that confuse new C programmers, including control structures, variable types, pointers, arrays, structs, linked lists, and recursion. It discusses each concept in 1-3 paragraphs, explaining what they are and providing basic examples. It also covers debugging strategies such as printing variables, reducing complexity, and inserting early returns to isolate issues.
Need done for Date Structures please! 4-18 LAB- Sorted number list imp.pdfinfo114
Need done for Date Structures please!
4.18 LAB: Sorted number list implementation with linked lists
Step 1: Inspect the Node.h file
Inspect the class declaration for a doubly-linked list node in Node.h. Access Node.h by clicking
on the orange arrow next to main.cpp at the top of the coding window. The Node class has three
member variables:
a double data value,
a pointer to the next node, and
a pointer to the previous node.
Each member variable is protected. So code outside of the class must use the provided getter and
setter member functions to get or set a member variable.
Node.h is read only, since no changes are required.
Step 2: Implement the Insert() member function
A class for a sorted, doubly-linked list is declared in SortedNumberList.h. Implement the
SortedNumberList class's Insert() member function. The function must create a new node with
the parameter value, then insert the node into the proper sorted position in the linked list. Ex:
Suppose a SortedNumberList's current list is 23 47.25 86, then Insert(33.5) is called. A new node
with data value 33.5 is created and inserted between 23 and 47.25, thus preserving the list's
sorted order and yielding: 23 35.5 47.25 86
Step 3: Test in develop mode
Code in main() takes a space-separated list of numbers and inserts each into a SortedNumberList.
The list is displayed after each insertion. Ex: If input is
then output is:
Try various program inputs, ensuring that each outputs a sorted list.
Step 4: Implement the Remove() member function
Implement the SortedNumberList class's Remove() member function. The function takes a
parameter for the number to be removed from the list. If the number does not exist in the list, the
list is not changed and false is returned. Otherwise, the first instance of the number is removed
from the list and true is returned.
Uncomment the commented-out part in main() that reads a second input line and removes
numbers from the list. Test in develop mode to ensure that insertion and removal both work
properly, then submit code for grading. Ex: If input is
then output is:
main.cpp
#include <iostream>
#include <string>
#include <vector>
#include "Node.h"
#include "SortedNumberList.h"
using namespace std;
void PrintList(SortedNumberList& list);
vector<string> SpaceSplit(string source);
int main(int argc, char *argv[]) {
// Read the line of input numbers
string inputLine;
getline(cin, inputLine);
// Split on space character
vector<string> terms = SpaceSplit(inputLine);
// Insert each value and show the sorted list's contents after each insertion
SortedNumberList list;
for (auto term : terms) {
double number = stod(term);
cout << "List after inserting " << number << ": " << endl;
list.Insert(number);
PrintList(list);
}
/*
// Read the input line with numbers to remove
getline(cin, inputLine);
terms = SpaceSplit(inputLine);
// Remove each value
for (auto term : terms) {
double number = stod(term);
cout << "List after removing " << number << ": " << endl;
list.Remove(number.
Arrays allow the storage and manipulation of multiple values of the same type. An array stores elements of the same type in a contiguous block of memory with indexes to access each element. One-dimensional arrays are declared with a size and accessed using indexes. Two-dimensional arrays represent tabular data and are accessed using row and column indexes. Arrays of objects allow storing and accessing multiple objects, and their elements can be accessed and manipulated similarly to primitive arrays.
C programming language allows for the declaration of arrays, which can store a fixed number of elements of the same data type. Arrays provide an efficient way to store and access related data sequentially in memory. Individual elements in an array are accessed via an index, and multi-dimensional arrays can model tables of data with multiple indices to access each element.
DATA STRUCTURE CLASS 12 COMPUTER SCIENCEDev Chauhan
Arrays, stacks, queues, and linked lists are common data structures in computer science. Arrays allow direct access to elements but have fixed size, while linked lists can dynamically grow and shrink but require traversing nodes sequentially. Stacks follow LIFO (last in first out) and queues follow FIFO (first in first out) ordering for inserting and removing elements. Linked lists store data in nodes that link to the next node, allowing efficient insertion/removal anywhere in the list. Common operations on these structures include push/pop for stacks, enqueue/dequeue for queues, and insert/delete nodes for linked lists.
The document discusses representing sparse matrices using linked lists. Sparse matrices have mostly zero values, so they are more efficiently represented by only storing the non-zero elements and their indices rather than all elements. This can save memory and computing time. The document provides examples of representing a sparse matrix using arrays or linked lists, with the linked list approach storing each non-zero element as a node with fields for row, column, value, and a pointer to the next node.
Pointers allow programs to store and manipulate memory addresses. A pointer variable contains the address of another variable. Pointers are useful for passing data between functions, returning multiple values from functions, and dynamically allocating memory at runtime. Pointers can also be used to access elements of arrays indirectly and implement multidimensional arrays more efficiently. Pointer notation provides an alternative way to access array elements through pointer arithmetic rather than subscripts.
This document provides an overview of key Python concepts including numbers, strings, variables, lists, tuples, dictionaries, and sets. It defines each concept and provides examples. Numbers discusses integer, float, and complex data types. Strings covers string operations like accessing characters, concatenation, formatting and methods. Variables explains variable naming rules and scopes. Lists demonstrates accessing, modifying, and sorting list elements. Tuples describes immutable ordered collections. Dictionaries defines storing and accessing data via keys and values. Sets introduces unordered unique element collections.
Pointer variables contain memory addresses that point to other variables in memory. A pointer contains the address of another variable. Pointers provide indirect access to data in memory. Pointer variables must be declared with a data type and the * symbol indicates it is a pointer. The & operator returns the memory address of a variable and * dereferences a pointer to access the value at that memory address. Pointers can be assigned, compared, and perform arithmetic operations like incrementing to point to the next memory location.
C++ - UNIT_-_IV.pptx which contains details about PointersANUSUYA S
Pointer is a variable in C++ that holds the address of another variable. Pointers allow accessing the memory location of other variables. There are different types of pointers based on the data type they are pointing to such as integer, character, class etc. Pointers are declared using an asterisk * before the pointer variable name. The address of a variable can be assigned to a pointer using the & address of operator. Pointers can be used to access members of a class and pass arrays to functions. The this pointer represents the address of the object inside member functions. Virtual functions allow dynamic binding at runtime in inheritance.
An array is a contiguous block of memory that stores elements of the same data type. Arrays allow storing and accessing related data collectively under a single name. An array is declared with a data type, name, and size. Elements are accessed via indexes that range from 0 to size-1. Common array operations include initialization, accessing elements using loops, input/output, and finding highest/lowest values. Arrays can be single-dimensional or multi-dimensional. Multi-dimensional arrays represent matrices and elements are accessed using multiple indexes. Common array applications include storing student marks, employee salaries, and matrix operations.
The document discusses arrays and array data structures. It defines an array as a set of index-value pairs where each index maps to a single value. It then describes the common array abstract data type (ADT) with methods like create, retrieve, and store for manipulating arrays. The document also discusses sparse matrix data structures and provides an ADT for sparse matrices with methods like create, transpose, add, and multiply.
C programming language provides arrays as a data structure to store a fixed-size collection of elements of the same type. An array stores elements in contiguous memory locations. Individual elements in an array can be accessed using an index. Common array operations in C include declaration, initialization, accessing and modifying individual elements, and passing arrays to functions.
Here are the steps to solve this problem:
1. Convert both lists of numbers to sets:
set1 = {11, 2, 3, 4, 15, 6, 7, 8, 9, 10}
set2 = {15, 2, 3, 4, 15, 6}
2. Find the intersection of the two sets:
intersection = set1.intersection(set2)
3. The number of elements in the intersection is the number of similar elements:
similarity = len(intersection)
4. Print the result:
print(similarity)
The similarity between the two sets is 4, since they both contain the elements {2, 3, 4, 15}.
The document discusses the concepts of SAP-1 (Simple Assembly Processor 1), a simple computer designed for educational purposes. It describes the components of SAP-1 including the program counter, memory, instruction register, accumulator, controller, and their functions. The timing diagrams for the fetch cycle are explained in detail over three states - address state, increment state, and memory state. The document also lists the instruction set of SAP-1 and provides an example program to demonstrate how it works.
Biological neurons and artificial neurons (ANN) both perform tasks like pattern recognition, learning, and generalization. ANNs are algorithmic models of biological neural systems and are composed of interconnected artificial neurons (nodes). ANNs can be trained with supervised, unsupervised, or reinforcement learning. They have applications in tasks like classification, pattern matching, and time series prediction.
This document provides an overview of the IT201 Basics of Intelligent Systems course. The course covers AI concepts like intelligent agents, problem solving using search and heuristics, knowledge representation, and branches of AI. It lists required textbooks and reference books. The first module introduces concepts like the definitions of AI, thinking humanly via cognitive modeling, thinking rationally using logic, acting humanly via the Turing test, and acting rationally as rational agents. It also describes the foundations of AI and typical applications.
A doubly linked list contains an extra pointer called the previous pointer in addition to the next pointer and data of a singly linked list. This allows traversal in both forward and backward directions and more efficient deletion when the node to delete is known. However, it requires extra space for the previous pointer and operations are slightly more complex as the previous pointers must be maintained. A node in a doubly linked list contains data, next and previous pointers. To insert a node after a given node, its next and previous pointers are adjusted and the previous pointer of the new node's next node is also updated.
The document discusses evaluating arithmetic expressions in infix notation using stacks. It explains that two stacks will be used - an operand stack to store numbers and an operator stack to store operators. It then provides the step-by-step process for evaluating an expression using these stacks by popping operands, popping operators, and pushing results. An algorithm is given that iterates through the expression character by character, pushing operands and operators to the appropriate stacks according to precedence rules.
A New Multi-Level Inverter Topology With Reduced Switch.pptxshashankbhadouria4
This document presents a new multi-level inverter topology that aims to reduce the number of switches needed. It contains an abstract, introduction, literature review, objectives, problem formulation, solution methodologies, description of a multi-level inverter, results and conclusions, future scope, and references sections. The project was submitted by four students under the guidance of three advisors and analyzes a new type of multi-level inverter circuit with fewer switches.
This document summarizes a student project on a multilevel inverter topology with reduced switch count. It presents the design of a three-phase 15-level voltage source inverter using three DC voltage sources and 10 switches. Simulation results show that this topology reduces total harmonic distortion to 4.71% compared to 72.86% for a two-level inverter. While requiring more switches, multilevel inverters allow generating higher voltages using lower-rated devices and produce waveforms closer to sinusoidal with lower harmonic losses.
This document discusses generating different types of signals in MATLAB and performing linear and circular convolution on two sequences. The goal is to write a MATLAB program that can generate signals, perform linear convolution of two sequences using a circular matrix method, and perform circular convolution between two sequences.
This document provides an introduction to data structures and algorithms. It begins by discussing how to create programs through requirements analysis, design, coding, testing, and debugging. It then defines data structures as how data is organized and operated on, and explains that learning data structures and algorithms is important for performing tasks efficiently. Examples are provided to illustrate storing student data in an array and representing polynomials using arrays or linked lists. The document also covers searching arrays, recursive functions and binary search, abstract data types, performance analysis in terms of time and space complexity, and asymptotic notations for analyzing algorithms.
This document defines and provides examples of graphs and graph representations. It begins by discussing Euler's use of graphs to solve the Königsberg bridge problem. It then defines graphs formally as G=(V,E) with vertices V and edges E. Examples of undirected and directed graphs are given. Common graph terms like paths, cycles, and connectivity are defined. Methods of representing graphs through adjacency matrices and adjacency lists are described and examples are provided. Finally, the document briefly discusses graph traversal algorithms and the concept of weighted edges.
The document discusses trees and graphs data structures. It begins with introducing different types of trees like binary trees, binary search trees, threaded binary trees, and their various traversal algorithms like inorder, preorder and postorder traversals. It then discusses tree operations like copying trees, testing for equality. It also covers the satisfiability problem and how binary trees can be used to represent logical expressions to solve this problem. Finally, it discusses threaded binary trees where null links in a binary tree are replaced with threads, and how this allows for efficient inorder traversal in linear time.
This document summarizes Chapter 2 on arrays and structures from a textbook on data structures in C. It outlines key topics like the array abstract data type, structures and unions, polynomial and sparse matrix abstract data types, multidimensional arrays, and strings. Examples are provided on implementing arrays, structures, polynomials, and various operations like addition and multiplication on polynomials.
This document summarizes the summer training completed by Shashank Bhadouria at Crompton in Jaipur from June to July 2022. The training covered the manufacturing process of distribution transformers including preparing the core from CRGO steel sheets, winding the low and high voltage coils, insulating and assembling the core and coils, filling the tank with oil, and performing quality control tests. The objectives were to apply theoretical knowledge, observe the manufacturing process, and develop career skills relevant to distribution transformers.
This document provides information about the 220kV Grid Substation located in Kunda Ki Dhani, Jaipur, Rajasthan, India. It discusses the substation's incoming and outgoing feeders, bus bars, transformers, fire protection system, remote terminal units, and includes a single line diagram. The aim of the substation is to step down voltages from 220kV to 132kV and lower to distribute power to areas in and around Jaipur. Trainees visit the substation to learn about high voltage electricity transmission and distribution as well as protective devices.
Here are the key ethical issues involved and options available to the traffic constable in this situation:
Ethical Issues:
- Duty to enforce traffic rules vs humanitarian concern to help injured person receive medical care
- Strict vs lenient enforcement of rules based on person's financial ability
Options:
1. Strictly enforce rules - stop ambulance, issue challans for all offenses
2. Show leniency - let ambulance pass, issue warning instead of challans due to emergency and person's inability to pay
3. Issue challan only for serious offenses like jumping red light, let helmet offense pass in emergency
4. Escort ambulance to hospital to ensure speedy travel but still issue warning
The constable
Here are the key ethical issues involved and options available to the traffic constable in this situation:
Ethical Issues:
- Duty to enforce traffic rules vs humanitarian concern to help injured person receive medical care
- Strict vs lenient enforcement of rules based on person's financial ability
Options:
1. Strictly enforce rules - stop ambulance, issue challans for all offenses
2. Show leniency - let ambulance pass, issue warning instead of challans due to emergency and person's inability to pay
3. Issue challan only for serious offenses like jumping red light, let helmet offense pass in emergency
4. Escort ambulance to hospital to ensure speedy travel but still issue warning
The constable
A stack is a data structure that follows the last-in, first-out (LIFO) principle. It can be implemented using arrays or linked lists. The key operations on a stack are push to add an element, pop to remove an element, checking if the stack is empty, and checking if the stack is full. The document provides code examples to demonstrate implementing a stack using an array or linked list, including functions for the basic stack operations.
The document discusses data structures and algorithms. It begins by introducing data structures and how they organize data to enable efficient operations. It provides examples of using arrays and linked lists to represent polynomials. The document then covers searching algorithms like binary search and recursive functions. It discusses abstract data types and how they separate an object's specification from its implementation. Finally, it covers analyzing algorithms, including analyzing their time and space complexity using asymptotic notations.
ACEP Magazine edition 4th launched on 05.06.2024Rahul
This document provides information about the third edition of the magazine "Sthapatya" published by the Association of Civil Engineers (Practicing) Aurangabad. It includes messages from current and past presidents of ACEP, memories and photos from past ACEP events, information on life time achievement awards given by ACEP, and a technical article on concrete maintenance, repairs and strengthening. The document highlights activities of ACEP and provides a technical educational article for members.
Using recycled concrete aggregates (RCA) for pavements is crucial to achieving sustainability. Implementing RCA for new pavement can minimize carbon footprint, conserve natural resources, reduce harmful emissions, and lower life cycle costs. Compared to natural aggregate (NA), RCA pavement has fewer comprehensive studies and sustainability assessments.
Embedded machine learning-based road conditions and driving behavior monitoringIJECEIAES
Car accident rates have increased in recent years, resulting in losses in human lives, properties, and other financial costs. An embedded machine learning-based system is developed to address this critical issue. The system can monitor road conditions, detect driving patterns, and identify aggressive driving behaviors. The system is based on neural networks trained on a comprehensive dataset of driving events, driving styles, and road conditions. The system effectively detects potential risks and helps mitigate the frequency and impact of accidents. The primary goal is to ensure the safety of drivers and vehicles. Collecting data involved gathering information on three key road events: normal street and normal drive, speed bumps, circular yellow speed bumps, and three aggressive driving actions: sudden start, sudden stop, and sudden entry. The gathered data is processed and analyzed using a machine learning system designed for limited power and memory devices. The developed system resulted in 91.9% accuracy, 93.6% precision, and 92% recall. The achieved inference time on an Arduino Nano 33 BLE Sense with a 32-bit CPU running at 64 MHz is 34 ms and requires 2.6 kB peak RAM and 139.9 kB program flash memory, making it suitable for resource-constrained embedded systems.
International Conference on NLP, Artificial Intelligence, Machine Learning an...gerogepatton
International Conference on NLP, Artificial Intelligence, Machine Learning and Applications (NLAIM 2024) offers a premier global platform for exchanging insights and findings in the theory, methodology, and applications of NLP, Artificial Intelligence, Machine Learning, and their applications. The conference seeks substantial contributions across all key domains of NLP, Artificial Intelligence, Machine Learning, and their practical applications, aiming to foster both theoretical advancements and real-world implementations. With a focus on facilitating collaboration between researchers and practitioners from academia and industry, the conference serves as a nexus for sharing the latest developments in the field.
Harnessing WebAssembly for Real-time Stateless Streaming PipelinesChristina Lin
Traditionally, dealing with real-time data pipelines has involved significant overhead, even for straightforward tasks like data transformation or masking. However, in this talk, we’ll venture into the dynamic realm of WebAssembly (WASM) and discover how it can revolutionize the creation of stateless streaming pipelines within a Kafka (Redpanda) broker. These pipelines are adept at managing low-latency, high-data-volume scenarios.
Advanced control scheme of doubly fed induction generator for wind turbine us...IJECEIAES
This paper describes a speed control device for generating electrical energy on an electricity network based on the doubly fed induction generator (DFIG) used for wind power conversion systems. At first, a double-fed induction generator model was constructed. A control law is formulated to govern the flow of energy between the stator of a DFIG and the energy network using three types of controllers: proportional integral (PI), sliding mode controller (SMC) and second order sliding mode controller (SOSMC). Their different results in terms of power reference tracking, reaction to unexpected speed fluctuations, sensitivity to perturbations, and resilience against machine parameter alterations are compared. MATLAB/Simulink was used to conduct the simulations for the preceding study. Multiple simulations have shown very satisfying results, and the investigations demonstrate the efficacy and power-enhancing capabilities of the suggested control system.
Literature Review Basics and Understanding Reference Management.pptxDr Ramhari Poudyal
Three-day training on academic research focuses on analytical tools at United Technical College, supported by the University Grant Commission, Nepal. 24-26 May 2024
Electric vehicle and photovoltaic advanced roles in enhancing the financial p...IJECEIAES
Climate change's impact on the planet forced the United Nations and governments to promote green energies and electric transportation. The deployments of photovoltaic (PV) and electric vehicle (EV) systems gained stronger momentum due to their numerous advantages over fossil fuel types. The advantages go beyond sustainability to reach financial support and stability. The work in this paper introduces the hybrid system between PV and EV to support industrial and commercial plants. This paper covers the theoretical framework of the proposed hybrid system including the required equation to complete the cost analysis when PV and EV are present. In addition, the proposed design diagram which sets the priorities and requirements of the system is presented. The proposed approach allows setup to advance their power stability, especially during power outages. The presented information supports researchers and plant owners to complete the necessary analysis while promoting the deployment of clean energy. The result of a case study that represents a dairy milk farmer supports the theoretical works and highlights its advanced benefits to existing plants. The short return on investment of the proposed approach supports the paper's novelty approach for the sustainable electrical system. In addition, the proposed system allows for an isolated power setup without the need for a transmission line which enhances the safety of the electrical network
A review on techniques and modelling methodologies used for checking electrom...nooriasukmaningtyas
The proper function of the integrated circuit (IC) in an inhibiting electromagnetic environment has always been a serious concern throughout the decades of revolution in the world of electronics, from disjunct devices to today’s integrated circuit technology, where billions of transistors are combined on a single chip. The automotive industry and smart vehicles in particular, are confronting design issues such as being prone to electromagnetic interference (EMI). Electronic control devices calculate incorrect outputs because of EMI and sensors give misleading values which can prove fatal in case of automotives. In this paper, the authors have non exhaustively tried to review research work concerned with the investigation of EMI in ICs and prediction of this EMI using various modelling methodologies and measurement setups.
We have compiled the most important slides from each speaker's presentation. This year’s compilation, available for free, captures the key insights and contributions shared during the DfMAy 2024 conference.
Manufacturing Process of molasses based distillery ppt.pptx
Chap 2 Arrays and Structures.pptx
1. Chapter 2 Arrays and Structures
Instructors:
C. Y. Tang and J. S. Roger Jang
All the material are integrated from the textbook "Fundamentals of Data Structures
in C" and some supplement from the slides of Prof. Hsin-Hsi Chen (NTU).
2. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
3. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
4. Arrays
Array: a set of index and value
data structure
For each index, there is a value associated with
that index.
representation (possible)
implemented by using consecutive memory.
5. Abstract Data Type Array
Structure Array is
objects : a set of pairs <index, value>
where for each value of index there is a value from the set item.
functions:
Array Create (j, list) : an array of j dimensions, where list is a j-tuple whose
ith element is the size of the ith dimension.
Item Retrieve (A, i) : If (i ε index) return the item indexed by i in array A,
else return error.
Array Store (A, i, x) : If (i ε index) insert <i, x> and return the new array,
else return error.
end Array
6. Implementation in C
int list[5], *plist[5];
Variable Memory Address
list[0] base address = α
list[1] α + sizeof(int)
list[2] α + 2*sizeof(int)
list[3] α + 3*sizeof(int)
list[4] α + 4*sizeof(int)
The names of
the five array
elements
Assume the memory address α = 1414, list[0] = 6, list[2] = 8, plist[3] = list = 1414
printf(“%d”, list); // 1414, the variable “list” is the pointer to an int
printf(“%d”, &list[0]) // 1414, return the address using “&”
printf(“%d”, list[0]); // 6, the value stored in the address “&list[0]”
printf(“%d”, (list + 2)); // 1414 + 2*sizeof(int), “(list +2)” is a pointer
printf(“%d”, *(list + 2)); // 8
printf(“%d”, plist[3]); // 1414, the value of a pointer is an address
printf(“%d”, *plist[3]); // 6
7. Example: One-dimensional
array accessed by address
call print1(&one[0], 5)
void print1(int *ptr, int rows)
{
/* print out a one-dimensional array using a pointer */
int i;
printf(“Address Contentsn”);
for (i=0; i < rows; i++)
printf(“%8u%5dn”, ptr+i, *(ptr+i));
printf(“n”);
}
int one[] = {0, 1, 2, 3, 4};
Goal: print out address and value
8. Example: Array program
#define MAX_SIZE 100
float sum(float [], int);
float input[MAX_SIZE], answer;
int i;
void main (void)
{
for (i = 0; i < MAX_SIZE; i++)
input[i] = i;
answer = sum(input, MAX_SIZE);
printf("The sum is: %fn", answer);
}
float sum(float list[], int n)
{
int i;
float tempsum = 0;
for (i = 0; i < n; i++)
tempsum += list[i];
return tempsum;
}
Result :
The sum is: 4950.000000
9. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
10. Structures (Records)
struct {
char name[10]; // a name that is a character array
int age; // an integer value representing the age of the person
float salary; // a float value representing the salary of the individual
} person;
strcpy(person.name, “james”);
person.age=10;
person.salary=35000;
An alternate way of grouping data that permits the
data to vary in type.
Example:
11. Create structure data type
typedef struct human_being {
char name[10];
int age;
float salary;
};
or
typedef struct {
char name[10];
int age;
float salary
} human_being;
human_being person1, person2;
12. Example: Embed a structure
within a structure
typedef struct {
int month;
int day;
int year;
} date;
typedef struct human_being {
char name[10];
int age;
float salary;
date dob;
};
person1.dob.month = 2;
person1.dob.day = 11;
person1.dob.year = 1944;
13. Unions
Similar to struct, but only one field is active.
Example: Add fields for male and female.
typedef struct sex_type {
enum tag_field {female, male} sex;
union {
int children;
boolean beard;
} u;
};
typedef struct human_being {
char name[10];
int age;
float salary;
date dob;
sex_type sex_info;
}
human_being person1, person2;
person1.sex_info.sex = male;
person1.sex_info.u.beard = FALSE;
person2.sex_info.sex = female;
person2.sex_info.u.children = 4;
14. Self-Referential Structures
One or more of its components is a pointer to itself.
typedef struct list {
char data;
list *link;
};
list item1, item2, item3;
item1.data=‘a’;
item2.data=‘b’;
item3.data=‘c’;
item1.link=item2.link=item3.link=NULL;
a b c
Construct a list with three nodes
item1.link=&item2;
item2.link=&item3;
malloc: obtain a node
15. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
16. Implementation on other data types
Arrays are not only data structures in their own right, we can
also use them to implement other abstract data types.
Some examples of the ordered (linear) list :
- Days of the week: (Sunday, Monday, Tuesday, Wednesday, Thursday, Friday, Saturday).
- Values in a deck of cards: (Ace, 2, 3, 4, 5, 6, 7, 8, 9, 10, Jack, Queen, King)
- Floors of a building: (basement, lobby, mezzanine, first, second)
Operations on lists :
- Finding the length, n , of the list.
- Reading the items from left to right (or right to left).
- Retrieving the ith element from a list, 0 ≦ i < n.
- Replacing the ith item of a list, 0 ≦ i < n.
- Inserting a new item in the ith position of a list, 0 ≦ i < n.
- Deleting an item from the ith position of a list, 0 ≦ i < n.
17. Abstract data type Polynomial
Structure Polynomial is
objects: ; a set of ordered pairs of <ei,ai>
where ai in Coefficients and ei in Exponents, ei are integers >= 0
functions:
for all poly, poly1, poly2 Polynomial, coef Coefficients, expon Exponents Polynomial
Zero( ) ::= return the polynomial, p(x) = 0
Boolean IsZero(poly) ::= if (poly) return FALSE else return TRUE
Coefficient Coef(poly, expon) ::= if (expon poly) return its coefficient
else return Zero
Exponent Lead_Exp(poly) ::= return the largest exponent in poly
Polynomial Attach(poly,coef, expon) ::= if (expon poly) return error
else return the polynomial poly with the term
<coef, expon> inserted
Polynomial Remove(poly, expon) ::= if (expon poly) return the polynomial poly with
the term whose exponent is expon deleted
else return error
Polynomial SingleMult(poly, coef, expon) ::= return the polynomial poly • coef • xexpon
Polynomial Add(poly1, poly2) ::= return the polynomial poly1 +poly2
Polynomial Mult(poly1, poly2) ::= return the polynomial poly1 • poly2
End Polynomial
n
e
n
e
x
a
x
a
x
p
...
)
( 1
1
degree : the largest exponent of a polynomial
18. Two types of Implementation for the
polynomial ADT
Type I :
#define MAX_DEGREE 1001
typedef struct {
int degree;
float coef[MAX_DEGREE];
} polynomial;
polynomial a;
a.degree = n
a. coef[i] = an-i , 0 ≦ i ≦ n.
Type II :
MAX_TERMS 1001 /* size of terms array */
typedef struct {
float coef;
int expon;
} polynomial;
polynomial terms[MAX_TERMS];
int avail = 0; /* recording the available space*/
starta finisha startb finishb avail
coef 2 1 1 10 3 1
exp 1000 0 4 3 2 0
0 1 2 3 4 5 6
advantage: easy implementation
disadvantage: waste space when sparse
storage requirements: start, finish, 2*(finish-start+1)
nonparse: twice as much as Type I
when all the items are nonzero
PA=2x1000+1
PB=x4+10x3+3x2+1
Poly A
coef 1 … 0 0 2
exp (index) 0 … 998 999 1000
Poly B
coef 1 0 3 10 1 … 0
exp (index) 0 1 2 3 4 … 1000
19. Polynomials addition of Type-I
/* d =a + b, where a, b, and d are polynomials */
d = Zero( )
while (! IsZero(a) && ! IsZero(b)) do {
switch COMPARE (Lead_Exp(a), Lead_Exp(b)) {
case -1: d =
Attach(d, Coef (b, Lead_Exp(b)), Lead_Exp(b));
b = Remove(b, Lead_Exp(b));
break;
case 0: sum = Coef (a, Lead_Exp (a)) + Coef ( b, Lead_Exp(b));
if (sum) {
Attach (d, sum, Lead_Exp(a));
a = Remove(a , Lead_Exp(a));
b = Remove(b , Lead_Exp(b));
}
break;
case 1: d =
Attach(d, Coef (a, Lead_Exp(a)), Lead_Exp(a));
a = Remove(a, Lead_Exp(a));
}
}
insert any remaining terms of a or b into d
// case -1: Lead_exp(a) < Lead_exp(b)
// case 0: Lead_exp(a) = Lead_exp(b)
// case 1: Lead_exp(a) < Lead_exp(b)
20. Polynomials adding of Type I
// A utility function to return maximum of two
integers
int max(int m, int n) { return (m > n)? m: n; }
// A[] represents coefficients of first polynomial
// B[] represents coefficients of second polynomial
// m and n are sizes of A[] and B[] respectively
int *add(int A[], int B[], int m, int n)
{
int size = max(m, n);
int *sum = new int[size];
// Initialize the porduct polynomial
for (int i = 0; i<m; i++)
sum[i] = A[i];
// Take ever term of first polynomial
for (int i=0; i<n; i++)
sum[i] += B[i];
return sum;
}
// Driver program to test above functions
int main()
{
// The following array represents polynomial 5 + 10x^2 +
6x^3
int A[] = {5, 0, 10, 6};
// The following array represents polynomial 1 + 2x + 4x^2
int B[] = {1, 2, 4};
int m = sizeof(A)/sizeof(A[0]);
int n = sizeof(B)/sizeof(B[0]);
printf("First polynomial is n“);
printPoly(A, m);
printf("nSecond polynomial is n“);
printPoly(B, n);
int *sum = add(A, B, m, n);
int size = max(m, n);
printf("nsum polynomial is n“) ;
printPoly(sum, size);
return 0;
}
void printPoly(int poly[], int n)
{
for (int i=0; i<n; i++)
{
cout << poly[i];
if (i != 0)
cout << "x^" << i ;
if (i != n-1)
cout << " + ";
}
}
21. Polynomial Multiplication
// A[] represents coefficients of first polynomial
// B[] represents coefficients of second polynomial
// m and n are sizes of A[] and B[] respectively
int *multiply(int A[], int B[], int m, int n)
{ int *prod = new int[m+n-1];
// Initialize the porduct polynomial
for (int i = 0; i<m+n-1; i++)
prod[i] = 0;
// Multiply two polynomials term by term
// Take ever term of first polynomial
for (int i=0; i<m; i++)
{ // Multiply the current term of first polynomial
// with every term of second polynomial.
for (int j=0; j<n; j++)
prod[i+j] += A[i]*B[j];
}
return prod;
}
// Driver program to test above functions
int main()
{
// The following array represents polynomial 5 + 10x^2
+ 6x^3
int A[] = {5, 0, 10, 6};
// The following array represents polynomial 1 + 2x +
4x^2
int B[] = {1, 2, 4};
int m = sizeof(A)/sizeof(A[0]);
int n = sizeof(B)/sizeof(B[0]);
cout << "First polynomial is n";
printPoly(A, m);
cout << "nSecond polynomial is n";
printPoly(B, n);
int *prod = multiply(A, B, m, n);
cout << "nProduct polynomial is n";
printPoly(prod, m+n-1);
return 0;
}
22. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
24. Abstract data type Sparse_Matrix
Structure Sparse_Matrix is
objects: a set of triples, <row, column, value>, where row and column are integers and form a
unique combination, and value comes from the set item.
functions:
for all a, b Sparse_Matrix, x item, i, j, max_col, max_row index
Sparse_Marix Create(max_row, max_col) ::=
return a Sparse_matrix that can hold up to max_items = max _row
max_col and whose maximum row size is max_row and whose maximum
column size is max_col.
Sparse_Matrix Transpose(a) ::=
return the matrix produced by interchanging the row and column value of
every triple.
Sparse_Matrix Add(a, b) ::=
if the dimensions of a and b are the same
return the matrix produced by adding corresponding items, namely those
with identical row and column values.
else return error
Sparse_Matrix Multiply(a, b) ::=
if number of columns in a equals number of rows in b
return the matrix d produced by multiplying a by b according to the formula:
d [i] [j] = (a[i][k]•b[k][j]) where d (i, j) is the (i,j)th element
else return error.
25. Sparse_Matrix Create and transpose
#define MAX_TERMS 101 /* maximum number of terms +1*/
typedef struct {
int col;
int row;
int value;
} term;
term a[MAX_TERMS]
for each row i (or column j)
take element <i, j, value> and
store it in element <j, i, value>
of the transpose.
row col value
a[0] 6 6 8
[1] 0 0 15
[2] 0 3 22
[3] 0 5 -15
[4] 1 1 11
[5] 1 2 3
[6] 2 3 -6
[7] 4 0 91
[8] 5 2 28
row col value
b[0] 6 6 8
[1] 0 0 15
[2] 0 4 91
[3] 1 1 11
[4] 2 1 3
[5] 2 5 28
[6] 3 0 22
[7] 3 2 -6
[8] 5 0 -15
Sparse matrix and its transpose stored as triples
#(rows)
#(columns)
#(nonzero entries)
any element within a matrix using the triple <row, col, value>
Difficulty:
what position to put <j, i, value> ?
26. Transpose of a sparse matrix in
O(columns*elements)
void transpose (term a[], term b[])
/* b is set to the transpose of a */
{
int n, i, j, currentb;
n = a[0].value; /* total number of elements */
b[0].row = a[0].col; /* rows in b = columns in a */
b[0].col = a[0].row; /*columns in b = rows in a */
b[0].value = n;
if (n > 0) { /*non zero matrix */
currentb = 1;
for (i = 0; i < a[0].col; i++)
/* transpose by columns in a */
for( j = 1; j <= n; j++)
/* find elements from the current column */
if (a[j].col == i) {
/* element is in current column, add it to b */
b[currentb].row = a[j].col;
b[currentb].col = a[j].row;
b[currentb].value = a[j].value;
currentb++
}
}
}
Scan the array “columns” times.
The array has “elements” elements.
==> O(columns*elements)
27. Analysis and improvement
Discussion: compared with 2-D array representation
O(columns*elements) vs. O(columns*rows)
#(elements) columns * rows, when the matrix is not sparse.
O(columns*elements) O(columns*columns*rows)
Problem: Scan the array “columns” times.
Improvement:
Determine the number of elements in each column of the original matrix.
=>
Determine the starting positions of each row in the transpose matrix.
28. Transpose of a sparse matrix in
O(columns + elements)
void fast_transpose(term a[ ], term b[ ])
{
/* the transpose of a is placed in b */
int row_terms[MAX_COL], starting_pos[MAX_COL];
int i, j, num_cols = a[0].col, num_terms = a[0].value;
b[0].row = num_cols; b[0].col = a[0].row;
b[0].value = num_terms;
if (num_terms > 0){ /*nonzero matrix*/
for (i = 0; i < num_cols; i++)
row_terms[i] = 0;
for (i = 1; i <= num_terms; i++)
row_terms[a[i].col]++
starting_pos[0] = 1;
for (i =1; i < num_cols; i++)
starting_pos[i]=starting_pos[i-1] +row_terms [i-1];
for (i=1; i <= num_terms, i++) {
j = starting_pos[a[i].col]++;
b[j].row = a[i].col;
b[j].col = a[i].row;
b[j].value = a[i].value;
}
}
}
O(num_cols)
O(num_terms)
O(num_cols-1)
O(num_terms)
O(columns + elements)
29. Sparse matrix multiplication
void mmult (term a[ ], term b[ ], term d[ ] )
/* multiply two sparse matrices */
{
int i, j, column, totalb = b[].value, totald = 0;
int rows_a = a[0].row, cols_a = a[0].col,
totala = a[0].value; int cols_b = b[0].col,
int row_begin = 1, row = a[1].row, sum =0;
int new_b[MAX_TERMS][3];
if (cols_a != b[0].row){
fprintf (stderr, “Incompatible matricesn”);
exit (1);
}
fast_transpose(b, new_b);
/* set boundary condition */
a[totala+1].row = rows_a;
new_b[totalb+1].row = cols_b;
new_b[totalb+1].col = 0;
for (i = 1; i <= totala; ) {
column = new_b[1].row;
for (j = 1; j <= totalb+1;) {
/* mutiply row of a by column of b */
if (a[i].row != row) {
storesum(d, &totald, row, column, &sum);
i = row_begin;
for (; new_b[j].row == column; j++)
;
column =new_b[j].row
}
else if (new_b[j].row != column){
storesum(d, &totald, row, column, &sum);
i = row_begin;
column = new_b[j].row;
}
else switch (COMPARE (a[i].col, new_b[j].col)) {
case -1: /* go to next term in a */
i++; break;
case 0: /* add terms, go to next term in a and b */
sum += (a[i++].value * new_b[j++].value);
break;
case 1: /* advance to next term in b*/
j++
}
} /* end of for j <= totalb+1 */
for (; a[i].row == row; i++)
;
row_begin = i; row = a[i].row;
} /* end of for i <=totala */
d[0].row = rows_a;
d[0].col = cols_b; d[0].value = totald;
}
30. storesum function
void storesum(term d[ ], int *totald, int row, int column, int *sum)
{
/* if *sum != 0, then it along with its row and column
position is stored as the *totald+1 entry in d */
if (*sum)
if (*totald < MAX_TERMS) {
d[++*totald].row = row;
d[*totald].col = column;
d[*totald].value = *sum;
}
else {
fprintf(stderr, ”Numbers of terms in product exceed %dn”, MAX_TERMS);
exit(1);
}
}
32. Compared with classic multiplication
algorithm
for (i =0; i < rows_a; i++)
for (j=0; j < cols_b; j++) {
sum =0;
for (k=0; k < cols_a; k++)
sum += (a[i][k] *b[k][j]);
d[i][j] =sum;
}
O(rows_a * cols_a * cols_b)
mmult vs. classic
O(cols_b * totala + rows_a * totalb) vs. O(rows_a * cols_a * cols_b)
33. Matrix-chain multiplication
n matrices A1, A2, …, An with size
p0 p1, p1 p2, p2 p3, …, pn-1 pn
To determine the multiplication order such that # of scalar
multiplications is minimized.
To compute Ai Ai+1, we need pi-1pipi+1 scalar multiplications.
e.g. n=4, A1: 3 5, A2: 5 4, A3: 4 2, A4: 2 5
((A1 A2) A3) A4, # of scalar multiplications:
3 * 5 * 4 + 3 * 4 * 2 + 3 * 2 * 5 = 114
(A1 (A2 A3)) A4, # of scalar multiplications:
3 * 5 * 2 + 5 * 4 * 2 + 3 * 2 * 5 = 100
(A1 A2) (A3 A4), # of scalar multiplications:
3 * 5 * 4 + 3 * 4 * 5 + 4 * 2 * 5 = 160
34. Let m(i, j) denote the minimum cost for computing
Ai Ai+1 … Aj
Computation sequence :
Time complexity : O(n3)
m(1,4)
m(1,3) m(2,4)
m(1,2) m(2,3) m(3,4)
j
i
if
j
i
if
p
p
p
j)
1,
m(k
k)
m(i,
min
0
j)
m(i,
i
k
1
i
j
k
i
Matrix-chain multiplication (cont.)
35. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
36. Representation of multidimensional arrays
The internal representation of multidimensional arrays requires more
complex addressing formulas.
a[upper0] [upper1]…[uppern-1]
=> #(elements of a) =
There are two ways to represent multidimensional arrays:
row major order and column major order.
(row major order stores multidimensional arrays by rows)
Ex. A[upper0][upper1] : upper0 rows (row0, row1,… ,rowupper0-1),
each row containing upper1 elements
Assume that α is the address of A[0][0]
the address of A[i][0] : α+ i *upper1
A[i][j] : α+ i *upper1+j
1
0
n
i
i
upper
row major :
1 2 3 4
5 6 7 8
9 10 11 12
column major :
1 4 7 10
2 5 8 11
3 6 9 12
37. Representation of Multidimensional Arrays
(cont.)
n dimensional array addressing formula for A[i0][i1]…[in-1] :
Assume that the address of A[0][0]…[0] is α.
the address of A[i0][0][0]…[0] : α + i0*upper1*upper2*…*uppern-1
A[i0][i1][0]…[0] : α + i0*upper1*upper2*…*uppern-1
+ i1*upper2*upper3*…*uppern-1
A[i0][i1][i2]…[in-1] : α + i0*upper1*upper2*…*uppern-1
+ i1*upper2*upper3*…*uppern-1
+ i2*upper3*upper4*…*uppern-1
﹕
+ in-2*uppern-1
+ in-1
1
0
1
1
1
1
1
0
,
:
,
n
i
n
n
j
k
k
j
j
j
a
n
j
upper
a
where
a
i
38. Outline
The array as an abstract data type
Structures and unions
The polynomial abstract data type
The sparse matrix abstract data type
Representation of multidimensional arrays
The string abstract data type
39. The string abstract data type
Structure String is
objects : a finite set of zero or more characters.
functions :
for all s, t String, i, j, m non-negative integers
String Null(m) ::= return a string whose maximum length is m characters, but
initially set to NULL. We write NULL as “”.
Integer Compare(s, t) ::= if s equals t return 0
else if s precedes t return -1 else return +1
Boolean IsNull(s) ::= if (Compare(s, NULL)) return FALSE else return TRUE
Integer Length(s) ::= if (Compare(s, NULL)) return the number of characters in s
else return 0
String Concat(s, t) ::= if (Compare(t, NULL)) return a string whose elements are
those of s followed by those of t else return s
String Subset(s, i, j) ::= if ((j>0) && (i+j-1)<Length(s)) return the string containing
the characters of s at position i, i+1, …, i+j-1.
else return NULL.
41. String insertion function
void strnins(char *s, char *t, int i)
{
/* insert string t into string s at position i */
char string[MAX_SIZE], *temp = string;
if (i < 0 && i > strlen(s)) {
fprintf(stderr, ”Position is out of bounds n” );
exist(1);
}
if (!strlen(s))
strcpy(s, t);
else if (strlen(t)) {
strncpy(temp, s, i);
strcat(temp, t);
strcat(temp, (s+i));
strcpy(s, temp);
}
}
s → a m o b i l e 0
t → u t o 0
temp → 0
initially
temp → a 0
(a) after strncpy (temp, s, i)
temp → a u t o 0
(b) after strcat (temp, t)
temp → a u t o m o b i l e 0
(c) after strcat (temp, (s+i))
Example:
Never be used in practice, since it’s wasteful in use of time and space !
42. Pattern matching algorithm
(checking end indices first)
int nfind(char *string, char *pat)
{
/* match the lat character of pattern first, and then match from the beginning */
int i, j, start = 0;
int lasts = strlen(string) – 1;
int lastp = strlen(pat) – 1;
int endmatch = lastp;
for (i = 0; endmatch <= lasts; endmatch++, start++){
if (string[endmatch] == pat[lastp])
for (j = 0, i = start; j < lastp && string[i] == pat[j]; i++, j++)
;
if (j == lastp)
return start; /* successful */
}
return -1;
}
43. Simulation of nfind
a a b
↑ ↑
j lastp
(a) pattern
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(b) no match
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(c) no match
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(d) no match
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(e) no match
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(f) no match
a b a b b a a b a a
↑ ↑ ↑
start endmatch lasts
(g) match
44. Failure function used in KMP algorithm
Definition: If P = p0p1…pn-1 is a pattern, then its failure function, f, is defined as:
Example: pat = ‘abcabcacab’
A fast way to compute the failure function:
otherwise
j
f
,
1
)
(
Largest i < j such that p0p1…pi = pj-ipj-i-1…pj if such an i ≧ 0 exists
1
1
)
1
(
1
)
( j
f
j
f m
if j = 0
Where m is the least integer k for which
if there is no k satisfying the above
j
j
f
P
p k
1
)
1
(
j 0 1 2 3 4 5 6 7 8 9
pat a b c a b c a c a b
f -1 -1 -1 0 1 2 3 -1 0 1
45. KMP algorithm (1/5)
Case 1: the first symbol of P dose not appear again in P
Case 2: the first symbol of P appear again in P
46. KMP algorithm (2/5)
Case 3: not only the first symbol of P appears in P, prefixes of P appear in P twice