Real Time course experis קורס

53
ק ו ר סREAL TIME / EMBEDDED מ ב ח נ י ם ו ת ר ג י ל י כ י ת ה ו ב י תExperis Software

description

חומר רפרנס לקורס : מבחנים שאלות ותרגילים

Transcript of Real Time course experis קורס

Page 1: Real Time course experis קורס

REAL TIME / EMBEDDEDסרוק

תיבו התיכ יליגרתו םינחבמ

Experis Software

Page 2: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 3: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 4: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 5: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 6: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 7: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 8: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 9: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 10: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 11: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 12: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 13: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 14: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 15: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 16: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 17: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 18: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 19: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 20: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 21: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 22: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 23: Real Time course experis קורס

Experis Software Real Time / Embedded

Page 24: Real Time course experis קורס

TEST – OPERATION SYSTEMS I

1. Describe this program’s output:

#include <stdio.h>#include <unistd.h>#include <stdlib.h>

int g = 0;int n=0;int k=0;

int main(){

n = fork ();if (n<0){

/* Error */}else if (n>0) {

++g;printf ("Task a: g = %d\n" , g);

}else {

k = fork ();if (k<0){

/* Error */}else if (k>0) {

--g;printf ("Task b: g = s %d\n" , g);

}

}return 0;

}

2. Describe how system’s performance is influenced by doubling the quantum time.3. Describe all steps and stages conducted after left-clicking a mouse in a “Word” word processor.4. Describe the following: interrupt vector, reentrant code, polling, trap, preemptive algorithm.

Experis Software Real Time / Embedded

Page 25: Real Time course experis קורס

TEST – OPERATION SYSTEMS II

1. Describe the following: pipe, fifo, message queue, shared memory, signals, semaphores.2. Describe the difference between a mutex and a sempahore. Describe the difference between system 5 semaphores and posix semaphores.3. Provide a solution for read/write in the Dynamically allocated shared memory.

Exercise 1:

Input N (number of lines, for example 6) from keyboard;Write a function func1 () that outputs a triangle of height and width N which look like:

*********************

Write a function func2 () that outputs a triangle of N*2-1 lines which looks like:(In this example N = 4):

****************

Write a function func3 () that outputs a triangle of N lines which looks like:

****

************

********************

Exercise 2:

Write a function that reads a positive integer value, and computes the following sequence: If the number is even, halve it; if it's odd, then subtract 1. Repeat this process until the value is 1, printing out each value. Finally print out how many of these operations you’ve performed.

Example:

Initial value is 58Next value is 29Next value is 28

Experis Software Real Time / Embedded

Page 26: Real Time course experis קורס

Next value is 14Next value is 7Next value is 6Next value is 3Next value is 2Next value is 1

Final value 1, number of steps 8

String Exercises

Write a function that prompts the user for a string, and prints its reverse.

Example:Input: Super SonicOutput: cinoS repuS

Write a function that prompts the user for a sentence, and prints each word on its own line:

Example:Input: Super SonicOutput: Super

Sonic

Write a program which receives input from keyboard of any decimal/binary number, converts it to binary/decimal and prints out the result:

First ask whether input is decimal or binaryExample for decimal input:Input: 4Output: 100Example for binary input:Input: 1110Output: 14

Program has to work as infinitive loop. The exit condition from the loop is input of any negative number.

Write a function named squeeze (s1, s2) that deletes each character in string s1 that matches any character in string s2.

Example:

S1 = "ABCDEF"S2 = "CGRF"Output: s1 = "ABDE"

Experis Software Real Time / Embedded

Page 27: Real Time course experis קורס

HW 2

Write a function named replace which takes a pointer to a string as a parameter, and replaces all spaces in that string by a minus sign (multiple spaces also have to be changed by one minus sign). Example: char* like = "I like beer";replace (like);

Should set like to "I-like-beer”.

Write a function to find the number of times that a given word occurs in a sentence.Example: The word is "iphone".

The sentence is "My iphone is black and your iphone is white".The word "iphone" occurs twice.

The word is "is".The sentence is "My iphone is black and your iphone is white".The word "is" occurs twice.

The word is "black".The sentence is "My iphone is black and your iphone is whiteThe word “black “occurs once.

Write a function of this program performs arithmetic addition operation on strings, Example:

Input:String 1 "435"String 2 "29"Output:String: "464"

C Exercises

Anagram - Write c program to check whether two strings are anagrams or not, string is assumed to consist of alphabets only. Two words are said to be anagrams of each other if the letters from one word can be rearranged to form the other word.

Binary search - Write c program which searches element in sorted array of integers

Write a program to remove all comments from a C program. Examples:

1. /* This is a comment */2. /* here is another one

that spans two lines */3. i = /* a big number */ 123456;

Experis Software Real Time / Embedded

Page 28: Real Time course experis קורס

Exercise - Day Appointment Calendar

Build a working “Appointment Calendar” generation program. (AC)

Main requirements:

Each meeting contains start / end hours and meeting’s subjectStart / end hours – can be even float numbersSubject – any text stringEach day can contain any number of meetings – means that DAY is an array of meetingsMeetings can’t overlap (intersect)

Also provide the following functionality:∑ Insert appointment into AC∑ Remove appointment from AC∑ Find appointment in AC (by hour)∑ Clean AC∑ Array of meetings has to be sorted by start hour during meeting insert∑ Print AC.

Exercise - Complex Numbers Calculator

The task of this homework assignment is to create Complex Numbers Calculator which provides a set of logical and arithmetical functions for Complex Numbers The structure below defines such numbers.struct complex{

float real;float imag;

};

Provide the following functionality:∑ Addition∑ Subtraction∑ Multiplication∑ Division∑ Absolute value

If you’re not familiar with the algorithms, please find them on the Web.

Input:

This Calculator can get input from either file or keyboard

Example (for arithmetic operations):

Input line (in this format data written in file, or typed from keyboard)

2,3 + 4,-2

In your program you have to perform:c3 = Addition (c1, c2);

Experis Software Real Time / Embedded

Page 29: Real Time course experis קורס

Subtraction

Where:Complex c1,c2,c3 ;2,3 means that c1 is 2 + 3i4,-2 means that c2 is 4 - 2i

It means that you have to read all input as ASCII and analyze it.If you read ‘+’ then call function ‘Addition’.If you read ‘-’ then call function ‘Subtraction’

Etc...

Provide interactive program...

Homework - Time and Date.

Create 2 structures: cTime_t and cDate_t

a) struct cTime_t which describes time objects.

Time objects are built from seconds, minutes and hours. ThisObject describes only one day time (not more than 24 hours).

Functionality of cTime_t objects:∑ set a new time to an existing object∑ function that prints out the cTime_t object in following the formats:

a) format = 1 13:23:12b) format = 2 1:23:12 PM

∑ Functions to retrieve from object hour, minutes and seconds.∑ possibility to perform addition of one time object to

Another, Example: 18:00 + 9:00 = 3:00 (24 + 3). Note: result in the first object ( t1 = t1 + t2 )

b) struct cDate_t describes the date objects.

Functionality of class cDate_t:

∑ change date of existing object∑ function that prints out the cDate_t object in the following formats:

a) dd:2, mon:3, year:4 – 22/Jan/2001b) dd:2, mon:2, year:4 – 22/01/2001 //Europeanc) mon:2, dd:2, year:4 – 01/22/2001 //American

∑ Functions to retrieve day, month and year from object

To retrieve data from object:current day in month – 1..31

Experis Software Real Time / Embedded

Page 30: Real Time course experis קורס

current month 1..12current year- 2011 as an exampleday of year // 1-365(366)is year leap or not ( see explanation below )name of month // January,…, October,…

Notes:

1)use <time.h> for time & localtime functions.

time_t time_date;struct tm* current_time;

time_date = time(0); // current time in secondscurrent_time = localtime(&time_date);

Relevant data can be retrieved From struct tm.

current_time->tm_hour;current_time->tm_min;current_time->tm_sec;current_time->tm_mon + 1;

current_time->tm_mday;current_time->tm_year + 1900;

2)

Year is leap if !(year%4)

Exercise 1

Write a program that prints the last n lines of a text file, where n and the file name should be specified form command line input. By default n should be 5. You are allowed to read the whole file only once.

Exercise 2

Write a program which compares two files and prints out the lines where they differ. Ignore empty lines.

Exercise – Library Management System

General Description of the Library Management System

The system’s purpose is storing borrowers, books, and books’ lending status information. The system should keep track of borrower transactions, i.e., lending and returning books.

Provided solution has to pass compilation and linkage, and contain a well defined Testing Program for system’s features. Test Program has to allow any input data – no hard coding allowed.

Experis Software Real Time / Embedded

Page 31: Real Time course experis קורס

Book Attributes

Subject – Book’s category (e.g. computer science - networking) ISBN number - a unique 9-digit number assigned to each bookStatus - the availability of the book based on one of the following:

Out - the book is on lend – no available copiesAvailable - the book is in library and can be lent out

Borrower Attributes

Name - borrower's first and last name ID – borrower’s unique identification number Currently borrowed - a list of books that the borrower has on lent

Book Administration

Add a new book - Add a new book to the computer system. Allows multiple copies of booksRemove a book - Removes an existing book from the system – search by ISBN number.If the book is already out, it cannot be removed. Search for a book – Search book by ISBN number.

Exercise - Lottery

Write a program that reads the 6 lottery numbers (choose from 49, pay attention not to pick the same numbers) generated randomly. Program prints out a lottery card in the following way, for the following picked numbers: 2, 13,15,37,39, 41

1 2 3 4 5 6 7 8 9 100 - + - - - - - - - -1 - - + - + - - - - -2 - - - - - - - - - -3 - - - - - - + - + -4 + - - - - - - - -

Exercise

1. Write a function that reads text and counts the number of occurrences of a specified word.

Example: Look for the word “friend” in the following text:

Tomer is a friend of Gadi and a friend of Ron.

Function’s output:“The word friend appeared 2 times”

2. Write a function that reads text and counts all letters occurrences.

Example: count characters in the following text: “Hello World”

Experis Software Real Time / Embedded

Page 32: Real Time course experis קורס

Function’s output:

H 1W 1d 1e 1l 3o 2r 1w 1

Exercise – Animal Farm

Part I: Animal

All of farm’s animals have shared data, so a class has been offered to hold the data and activity shared within all animals. This class holds the following:

Animal’s nameAnimals ID

Activities required for this class:

Default constructor – inits name to blank and ID to 0Constructor with parameters: name and IDOperator > tests ID Operator ++ tests IDShow – pure virtual functions which shows object’s dataMakeSound – prints out animal’s distinct sound

Part II: Specific animal

Every animal’s type has been assigned with an ID numbers range:Cows: 1-1000Chickens: 1001-2000Ducks: 2001-3000

A derived class from class Animal has to be created for each of these animal types. This derived class holds the unique data for the specific animal type. ID number boundaries can be described using an enumerator such as enum{MIN_ID=1,MAX_ID=100} defined within the specific class.This class’ constructors will validate IDs according to boundaries and will issue an error message upon an attempt to create an animal with a wrong ID number, followed by request for a valid ID.This class also consists of a Show function which prints out the animal type followed by its details.A specific MakeSound function should also be implemented for each animal type’s class.

Additional functions may be added upon need.

Experis Software Real Time / Embedded

Page 33: Real Time course experis קורס

Exercise Big Numbers

Write a class BigNumber which performs arithmetic operations on integer numbers of ANY length( + , - , / , and * );

Phase I:Default constructorConstructor from char*Copy constructorDestructoroperator + for positive numbers.

Phase II:operator = from BigNumber objectoperator = from intoperators == , < , > function ‘Print’ for ‘big int ‘ number

Provide two Derived classes: one for big int numbers and another for big float numbers

Example:

BigNumber_t bi1 (“12345678654321324”);BigNumber _t bi2 (“156721321156”);BigNumber _t bi3 = bi1 + bi2;

Exercise Car

classes car_t , fiat_t, opel_t

The task is to create 2 types of classes:

a) class car_t which describes any kind of car.

Functionality of all cars: Implement in base or derived class

Constructors: default and by engine capacityDestructorGet car’s nameSet and get gear type (standard or auto)function that changes the speed flag (by numbers 1,2,3)1 speed 0-20km/hour2 speed 20-50km/hour3 speed 50-100km/hour

overloading "operator <" which compares objects by capacity. You can compare cars of different types function that compares 2 cars and returns true if both fromthe same company and false if from different.function which retrieves from object its current speedeach car has a unique ID

fiat_t is a car with standard gearopel_t is a car with auto gear

Experis Software Real Time / Embedded

Page 34: Real Time course experis קורס

Classes fiat_t and opel_t have to implement the functionality of class car_t , which can’t be implemented correctly in the base class.

City – Template exercise

Building_t – template class. ID of building can be of any type:Example: IDs can be integers (1, 3, 5, 7 2, 4…) or even strings "A10”, "17Bet"…

Functionality of class: setBuidingID and getBuildingID

Street_t – template class; is a container of buildings.ID of street can be of any type: strings "Herzl", or integers as in New York – 42, 20Functionality of class: setStreetID and getStreetID¸ AddBuilding2Street, getBuilding

City_t - template class; is container of streets ID of City can be of any type: strings "Herzl", or any other typeFunctionality of class: setCityID and getCityID¸ AddStreet, getStreet

Pay attention, that City is a container of containers (for example: city is list of streets which are vectors of buildings).

Build test which checks implementation of these classes.

Exercise - Class String

Phase I:

Implement class string_t with following functionality:

∑ default constructor∑ constructor from 'C' string∑ destructor∑ operator =∑ mem-function 'length' which returns string’s length∑ mem-function 'setString' which gets 'C' string as a parameter ∑ mem-function 'getString' which returns 'C' string∑ mem-function 'compare' which compares 2 string_t type objects

This function gets another string as a parameter and returns:0 - if they are equal1 - if the object string less than parameter2 - if the object greater than parameter

∑ mem-function 'contains' - returns 1 if substring is found, else returns 0∑ mem-function 'prepend' - prepends a character string (both from char* and string_t)

Experis Software Real Time / Embedded

Page 35: Real Time course experis קורס

Phase 2:

Add class string_t the following functionality:

∑ convert string to upper/lower case∑ operator () - conversion operator which returns char* ( internal data )∑ mem-function 'index' which an index of "Str" character string in string_t object.

If not found returns -1, else returns starting index of "Str" in string_t object.∑ operators: += from both char* and string_t∑ operator [ ] - returns string[i]. Performs boundaries check∑ Logical operators : > , < , >= , <=, == , += , !=∑ Add static data-members caseSens & expand_value.

caseSens determines operators case sensitivity ∑ Add string_t operator()(int start, uint len);

returns substring of ‘len’ length starting at 'start' index in original string Example: string_t str ="1234567890" ; str(5,4) returns string "6789"

∑ function which returns index of first occurrence of some character in string∑ function which returns index of last occurrence of some character in string∑ Logical operators & function Compare with case sensitive flag.

Exercise – Entertainment Console

Write an Entertainment Console that can produce copies of a DVDPlayer, a CDPlayer and VCRPlayer.

Each of these supports operations:∑ start∑ stop ∑ forward∑ rewind

Solution:

∑ Use the Abstract Factory Pattern to create players that support the same set of operations but have their own implementations. Using an Abstract Factory makes it possible to create whatever sort of player is needed next from the same client code.

∑ Use the Mediator Pattern to create a context within which the logic of the interactions between operations on the players is encapsulated.

Experis Software Real Time / Embedded

Page 36: Real Time course experis קורס

Exercise – Design Patterns

In a town there is only one bank which manages accounts of citizens.Each account contains:

∑ percent on deposit∑ Opening date∑ Saving period

There are 3 types of accounts:

∑ 2 years minimum account∑ Family account – accessed by family members∑ Stock Exchange investment account

Write a program in which when the bank performs operation it will notify relevant account owners:

∑ The bank decides to invest money in Stock exchange but only for accounts whichsaving period is 10 years and were open not more than 5 years ago.

∑ Bank decides to give bonus of 500 shekels only to family accounts.

∑ Bank sends message to all 2 years saving account owners to come to the bank for the meeting with clerk.

1) Program has to implement Singleton, Factory Method, Observer and Bridge Design Patterns. ∑ Bank is both Singleton and Subject∑ Create an Abstract Base Class (ABC) Account. All specific Accounts are derived from it. ∑ Think, in which class has to be a Factory Method?∑ Separate Implementation from Design for Accounts ( Bridge )

2) Testing program (main) has to be provided. Hard-coded input is forbidden3) STL usage is required (example: Pick the right STL container for holding Observers pointers and write

in comment was this specific container selected).

Exercise # 1: Process segments layout

Objectives:

∑ Various running process memory segments study

Stack

Heap

Data

Code (Text(

i. Each segment usage.

ii. Difference between them.

iii. Each segment behavior (allocation, growth) while process is running.

High

Low

Experis Software Real Time / Embedded

Page 37: Real Time course experis קורס

Write a simple main() function contains the following elements:

∑ Static function.

∑ Extern function.

∑ Heap variables.

∑ Local variables.

∑ Global variables.

∑ Static local variables

∑ Static global variables.

Questions:

Run the program and extract the address of each element using the single step debugger (or by printing

it to log file).

∑ Describe the heap growth while memory allocation.

∑ Describe the stack growth while using local variables.

∑ What is the address of the functions? Is there a different between static and extern functions?

∑ What is the address of the global variables? Is there a different between static local variables

and global variables?

(Optional part) Redo the above, for the following:

∑ Static library.

∑ Implicit shared object.

∑ Explicit shared object.

∑ Two Threads.

Note: Disable Address space’s random nature

sudo -i

sudo echo 0 > /proc/sys/kernel/randomize_va_space

Experis Software Real Time / Embedded

Page 38: Real Time course experis קורס

Exercise - Virtual address

Objectives:

∑ "Relative address" term understood

1. Given the two following processes (P1 is running before P2):

In P1: What is the meaning of the value written to "MyFile"?

In P2:

∑ What the program does?

∑ What is the printed value of j?

∑ Can you explain that result?

Note: Use two terminal instances for two processes.

Note: Disable Address space’s random nature.

sudo -i

sudo echo 0 > /proc/sys/kernel/randomize_va_space

P1#include <stdio.h>#include <stdlib.h>

int main(){

int i=5;int *pi = &i;

FILE *fp;fp = fopen("MyFile", "w");fprintf(fp, "%p\n", pi);fclose(fp);

sleep(30);

return 0;}

P2#include <stdio.h>#include <stdlib.h>

int main(){

int j = 400;int *pi = 0;

FILE *fp;fp = fopen("MyFile", "r");fscanf(fp,"%p", &pi);fclose(fp);

j+= *pi;printf("%d\n", j);

return 0;}

Experis Software Real Time / Embedded

Page 39: Real Time course experis קורס

Exercise - DataStorage

class DataStorage_t

class DataStorage_t - implements ‘mathematical’ DataStorage.

class DataStorage_t Functionality:

Constructors:Default Constructor with predefined dimensionConstructor from user provided dimensionDestructorCopy constructorassignment operatorInput/output operators ( << and >> ) for all built-in types: ds << k; and ds >> k;

Provide explanation whether the user needs functionality of copying DataStorage_t objects , and implement if necessary.

∑ DataStorage_t type objects implement dynamic growth. Expand value means internal buffer growth when full is at least by N bytes == expand value

∑ Data stored in DataStorage_t object’s actual size is kept∑ Implement functionality of object clear for further usage∑ Pay attention on class design ( const, virtual, reference and values as parameters or return types of

operators or functions )

int main(){

// How to write/read any user defined objects (example with class X)

DataStorage_t dtStor(sizeof(X)); // create with user capacity

dtStor.XpndValue(64); // internal buffer will grow by// 64 bytes when full.

X x1(3.14, "Igor", 'A');X x2;

dtStor << x1; // save X object in data storagecout << "x1 = " << x1 << endl; // print out just for debuggingdtStor.Reset(); // rewind internal pointerdtStor >> x2; // restore X object

cout << "x2 = " << x2 << endl; // check, that read data is OK

return 0;}

Experis Software Real Time / Embedded

Page 40: Real Time course experis קורס

Exercise - Memory Management

Implement a memory management system of two components:

∑ class memPage_t ∑ class memPool_t

memPage_t functionality:

memPage_t holds any data as a stream of bytes and points to next page of the same type

memPage_t type object construction methods:∑ by a default size ( for example 1024 bytes)∑ by a user provided size

memPage_t object type copy is forbiddenimplement get/set current position in memory pageimplement get page status:

∑ is page empty ∑ is page full∑ page actual size ( how many bytes really written in page)∑ page capacity ( length )

implement page data read∑ by current position (default)∑ by user-specified position

implement page data write∑ by current position (default)

functionality of memPool_t

memPool_t’s role is controlling data placement in memory page’s linked list.

memPool_t type object can be initialized by:∑ some default size of page∑ with any number of empty pages ( one by default)

memPool _t type object copy is forbiddenimplement get/set current position in memPool_t - bytes actually used in memPool_timplement get manager status:

∑ empty?∑ actual size of the object memPool_t ∑ number of memory pages∑ to get pointer to the first memory page

implement manager data readimplement manager data writeimplement memory pages create by demandimplement memory page’s default size set/get

Experis Software Real Time / Embedded

Page 41: Real Time course experis קורס

Example:

memPool_t type object contains 3 memPages.

1000 bytes length ( capacity)1000 bytes actual size

1000 bytes length ( capacity)1000 bytes actual size

1000 bytes length ( capacity)200 bytes actual size

First 2 pages are full, and in the last page, only 200 bytes are used.

So, memPool_t’s actual size is 2200 bytes.Actual size of first 2 pages is 1000 bytes, and actual size of last page is 200 bytes.

If a user now wants to write into memPool_t object 1500 bytes, memPool_t has to:∑ add 800 bytes to last page ( up to 1000 bytes), ∑ create a new page of size 1000 bytes ∑ write new page with700 bytes.

1000 bytes length ( capacity)700 bytes actual size

Exercise - Template class Stack

Implement template class “Stack” with the following functionality:

∑ Default constructor∑ destructor∑ Push∑ Pop∑ Peek

Use class “Link” ( linked list) to implement “Stack”Also this class has to be Template.Define class “List”, as a nested class of Stack - for “ Stack “ only a very little part of “List” functionality is required.

Template Container of Pointers to any type

This class is a template class, which receives 2 template parameters:a) T- data typeb) container<T> - STL container ( vector or list ) . You can implement one of the versions:

tContainer_t<T, vector<T*> > and tContainer_t<T, list<T*> > ortContainer_t<T, vector> and tContainer_t<T, list>

∑ Implement class tContainer_t - contains pointers to any type of objects

Experis Software Real Time / Embedded

Page 42: Real Time course experis קורס

∑ tContainer_t functionality

- default constructor- destructor- object copy is forbidden- array isEmpty- return number of elements in array- insert a new element at array’s end- return container’s first element - return container’s last element- find specific element by value (parameter is T value)

∑ Use STL algorithm “find if”. Such algorithm uses predicate written by user- remove specific element and return pointer to it (parameter is T value )- remove all elements (without deleting them)- remove and delete specific element (parameter is T value )- remove and delete all elements - operator []

∑ class vector has operator[] and list does not.∑ use operator typeid in order to implement operator [] for vector

and list in a different way

Notes:

1) example with "specific" element:

tContainer_t<int, vector<int*> iArr;int i = 5;int* ip = iArr.find(i);

2) - return pointer to element if succeeded and 0 otherwise3) Note: instead of <class> you have to use <typename> , example ( you’ll need it )

typedef typename X::iterator iter_t;

Exercise - Exception Handler

Implement template class TException_t - derived from standard C++ class exception

Implement the following additional functionality:

∑ thrown object ( meaning – instead of “throw i” to throw the object which contains 'i')∑ textual description of exception∑ the name of the source file from which exception was thrown ∑ the line number of this source file∑ reference to “previous” thrown object ( if before an INT was thrown, then now TException_t

object has to contain reference to such INT.

Write a test program which throws and catches exceptions of a TException_t type.

Experis Software Real Time / Embedded

Page 43: Real Time course experis קורס

Bit Operations – Exercises

Swap∑ Swap between A and B without using any temporary (Three ways).

Math∑ Compute the integer absolute value without branching (Three ways).∑ Check if a given integer value is power of two (Two ways – with/without LTB).∑ Add two numbers using bitwise operations (Two ways).∑ Print a given number in Binary representation.

Bit Count

∑ Count the number of ones in a binary representation. (Two ways – with/without LTB). Calculate complexity.

Bit Manipulation∑ Flip all bits in given number from start to end bit∑ Flip a single bit in a given number (Two ways – with/without LTB)∑ Flip a two bits in a given number (Two ways – with/without LTB)∑ Shift-left N times in a circular way

Exercise - Parser & Syntax/Semantic Analyzer

A Parser is a program which reads input ASCII files and analyzes them.A Parser reads input lines and divides them into tokens. The delimiter between tokens can be ‘blank(s)’ or ‘tab(s)’ characters. All tokens are divided into 2 kinds - predefined and user-defined. Following is a list of predefined tokens:

Predefined Types:“char”, “short”, “int”, “long”, “float”, “double”, “void”

Key words , group 1“if”, “else”, “for” , “while”

Key words , group 2“class”, “private”, “public”, “protected”, “main”, “const”, “virtual”

Operators:“++”, “--“, “==”, “->” , “=”, “+”, “-“, “*”, “&”, “<<”, “>>”

Following predefined tokens also play a role of delimiter:“(“, ”), “[“, “]” , “{“ , “}” “;” “<”, “>” , “=”, “+”, “-“, “*”, “&”

Example:if(a) really 4 tokens : 'if', '(' , 'a', ')'

Experis Software Real Time / Embedded

Page 44: Real Time course experis קורס

The Parser program has to count the number of input lines and tokens in an input file.

Syntax/Semantic analyzer has to check the syntax of each input line.Each input line can contain any number of characters. Each input line can contain more than one statement

Language Rules

The program has to start from "main()" function.

main() { // legal…

}

int i; // illegal - declaration before 'main'main() {

…}

Any sequence of tokens is legal except the list of Possible Errors ( see below).

Possible errors:

∑ Number of open braces doesn’t match number of close braces.([a) - is illegal ) ( - is illegal ‘(‘ has to be before ‘)’

∑ ‘else’ without ‘if’

∑ multiple Predefined Types::int short k; // error, short after intdouble char c; // error, char after double…

∑ illegal operators, examples:+++ // error, no operator +++<<<

∑ already declared:int k;float k; // error, variable 'k' already declared

Experis Software Real Time / Embedded

Page 45: Real Time course experis קורס

Example:

} // error, “}” without “{“int short k; // error, multiple typeelse a= b // error, “else” without “if”

// error, no 'main()' function before

main() // error, 'main' has to be the firstif (i<10) {

i=0;} else {

i++;}} // error, “}” without “{“

kkk >>> aaa // error, illegal operator “>>>”

Notes:

∑ Throw Texception object if file can't be open∑ Don't allow trailing errors

Exercise- STL

∑ Implement a template function Tops which takes an STL list of stacks as a parameter and returns a list as the function result of the tops of the stacks in the list. Remove the items from the stacks as well. The popped values are returned in the same order as they were on the stacks. Skip empty stacks.

∑ Implement a function prefixTo which takes a word and target (both STL strings) as parameters, and returns the start of the word up to the target. If the target isn’t a part of the word, return anempty string. For example, prefixTo("lipsticks", "s") would return ``lip'' and prefixTo("abc", "x") would return “”'.

∑ Implement a function mostCommon which takes a non-empty STL list of words (stored as strings) and returns the most frequent word in the list.

If there is more than one possible answer, it doesn't matter which is returned.

Experis Software Real Time / Embedded

Page 46: Real Time course experis קורס

Exercise – Vector

Given:

Struct Vector

{

int* m_Arr;size_t m_Arrsize; size_t m_ItemsNum; size_t m_Blocksize;

}

typedef enum

{

ERR_OK = 0,ERR_GENERAL, ERR_ALLOC_FAILED,ERR_REALLOC_FAILED,

ERR_NOT_INITIALIZED,VECTOR ERR,STACK ERR,ERR_END

} ADTErr;

void HandleError (ADTErr Error , const char* additional_msg[])

{

printf( "%s\n" , additional_msg[Error]);}

Implement the following:

Vector* VectorCreate (size_t , size_t );void VectorDestroy (Vector* );ADTErr VectorGet (Vector* , size_t , int* );ADTErr VectorSet (Vector* , size_t , int );ADTErr VectorItemsNum (Vector* , int* );ADTErr VectorAdd (Vector* , int );ADTErr VectorRemove (Vector* , int* );void VectorPrint (Vector* );

Experis Software Real Time / Embedded

Page 47: Real Time course experis קורס

Exercise – Stack

Given:

struct Stack

{

Vector* m_Vec;

};

Implement the following:

Stack* StackCreate (size_t , size_t ); void StackDestroy (Stack* );ADTErr StackPush (Stack* , int );ADTErr StackPop (Stack* , int* );ADTErr StackTop (Stack* , int* );int StackIsEmpty (Stack*);void StackPrint (Stack* );

Exercise – Queue

Given:

struct Queue

{

Vector* m_Vec;

};

Implement the following:

Queue* QueueCreate (size_t , size_t ); void QueueDestroy (Queue* );ADTErr QueueInsert (Queue * , int );ADTErr QueueRemove (Queue * , int* );int QueueIsEmpty (Queue *);void StackPrint (Queue * );

Exercise – Queue Wrapper

Implement Queue as a wrapper of Vector.

Experis Software Real Time / Embedded

Page 48: Real Time course experis קורס

Exercise – Linked List

Given:

struct Node{

int m_data;Node* m_next;Node* m_prev;

}

Struct List{

Node m_head; /*stub*/Node m_tail; /*stub*/

}

Implement the following:

List* ListCreate (); void ListDestroy (List* );ADTErr ListPushHead (List* , int ); ADTErr ListPushTail (List* , int );int ListPopHead (List* );int ListPopTail (List* );int ListCountItems (List* ); void ListPrint (List* );

Exercise – Binary Tree

Given:

struct Node{

int m_data;Node* m_left;Node* m_right;Node* m_parent;

};

struct Tree {

Node* m_root;

};

Implement the following:

Tree* TreeCreate (); void TreeDestroy (Tree* );ADTErr TreeInsert (Tree* , int ); int TreeIsDataFound (Tree* , int);void TreePrint (Tree* );

Experis Software Real Time / Embedded

Page 49: Real Time course experis קורס

Exercise – Heap (Wrapper on Vector)

Given:

struct Heap{

Vector* m_vec;} ;

Implement the following:

Heap* HeapBuild (Vector* ); void HeapDestroy (Heap* );ADTErr HeapInsert (Heap* , int ); ADTErr HeapMax (Heap* , int* ); ADTErr HeapExtractMax (Heap* , int* ); int HeapSize (Heap*);void HeapPrint (Heap* );

Exercise – HashMap

Given:

struct Pair{

int m_key;int* m_data;int m_status;

};

struct HashMap{

HF m_func;size_t m_count;Pair* m_array;size_t m_array_size;

};

typedef size_t (*HF)(int key);

Implement the following:

HashMap* HashMapCreate (HF , size_t );void HashMapDestroy (HashMap*);ADTErr HashMapInsert (HashMap* , int , int*);ADTErr HashMapRemove (HashMap* , int , int**); ADTErr HashMapGetValueByKey (HashMap* , int , int**); size_t HashMapSize (HashMap*);void HashMapPrint(HashMap*);

Experis Software Real Time / Embedded

Page 50: Real Time course experis קורס

Exercise – Sorting Algorithms

Implement the following sorting algorithms. Demonstrate on Vector.

void BubbleSort (int* , int);void QuickSort (int*, int, int);void InsertionSort (int* , int);void MergeSort (int* , int); void CountSort (int* , int , int); void RadixSort (int* , int );

Exercise – Graph

Given:

struct Graph {

Vector* m_vec;int mode; int** matrix;

};

Implement the following:

Graph* GraphCreate (Vector* , int ); void GraphDestroy (Graph* );ADTErr GraphConnect (Graph* , int , int ); ADTErr GraphDisconnect (Graph* , int , int ); ADTErr GraphConnectWT (Graph* , int , int , int ); ADTErr GraphChangeWT (Graph* , int , int , int); int GraphIsAdjacent (Graph* , int , int );ADTErr GraphIsPath (Graph* , int , int , int );

Experis Software Real Time / Embedded

Page 51: Real Time course experis קורס

Exercise – Generic Linked List

Given:

struct Node{

ListData* m_data;Node* m_next;Node* m_prev;

};

struct List {

Node m_head;Node m_tail;

};

typedef void ListData;typedef Node* ListItr;

Implement the following:

List* ListCreate (void); void ListDestroy (List* ); ADTErr ListPushHead (List* , ListData*); ADTErr ListPushTail (List* , ListData*);ListData* ListPopHead (List* );ListData* ListPopTail (List* );size_t ListCountItems (List* ); int ListIsEmpty (List*);ListItr ListBegin (List*); ListItr ListEnd (List*); ListItr ListNext (ListItr);ListItr ListPrev (ListItr);ListData* ListGetData (ListItr);ListItr ListInsertBefore (ListItr , ListData*);ListItr ListFindFirst (ListItr , ListItr , CF , ListData*);ListData* ListRemove (ListItr);ListItr ListForEach (ListItr , ListItr , DF , void*)

Exercise – Generic Vector

Given:

struct Vector /* Keep struct definition away from user */{

VectorData** m_Arr;size_t m_Arrsize;size_t m_ItemsNum;size_t m_Blocksize;

} ;

typedef void VectorData;

Experis Software Real Time / Embedded

Page 52: Real Time course experis קורס

Implement the following:

Vector* VectorCreate (size_t , size_t ); void VectorDestroy (Vector* );void VectorPrint (Vector* ); ADTErr VectorGet (Vector* , size_t , VectorData** );ADTErr VectorSet (Vector* , size_t , VectorData** );ADTErr VectorItemsNum (Vector* , int* ); ADTErr VectorAdd (Vector* , VectorData** ); ADTErr VectorRemove (Vector* , VectorData** );

Exercise – Generic Stack

Given:

struct Stack{

List* m_list;};

Implement the following:

Stack* StackCreate (void);void StackDestroy (Stack*);ADTErr StackPush (Stack* , void*); void* StackPop (Stack*); void* StackTop (Stack*); int StackIsEmpty (Stack*);void StackPrint (Stack* , void(*_Print)(void*));

Exercise – Generic Queue

Given:

struct Queue{

List* m_list;};

Implement the following:

Queue* QueueCreate (void);void QueueDestroy (Queue*);ADTErr QueueInsert (Queue* , void*); void* QueueRemove (Queue*); int QueueIsEmpty (Queue *);void Queue Print (Stack* , void(*_Print)(void*));

Experis Software Real Time / Embedded

Page 53: Real Time course experis קורס

Exercise – Generic Tree

Given:

struct Node{

TreeData* m_data;Node* m_parent;Node* m_sons[2];

};

struct Tree {

Node m_root; CF CompFunc;

}

typedef int (*CF)(TreeData* , TreeData*);typedef void (*DF)(TreeData* , void*);typedef Node* TreeItr;

Implement the following:

Tree* TreeCreate (CF); void TreeDestroy (Tree* );TreeItr TreeFind (Tree* , TreeData*); TreeItr TreeInsert (Tree* , TreeData*); int TreeCount (Tree*);TreeItr TreeBegin (Tree*); TreeItr TreeEnd (Tree*); TreeItr TreeNext (TreeItr); TreeItr TreePrev (TreeItr); TreeData* TreeGetData (TreeItr);TreeData* TreeRemove (TreeItr); TreeItr TreeForEach (Tree* , int , DF , void* );

Experis Software Real Time / Embedded