1 / 18

Informatik I (D-ITET) Group 7, 15:00-17:00, ETZ H91 Assistant: Ercan Ucan

Informatik I (D-ITET) Group 7, 15:00-17:00, ETZ H91 Assistant: Ercan Ucan. Slides at http://people.inf.ethz.ch/eucan/inf-1 /. Exercise 5 ( 29/10/2012 ) . Discussion on Series 4 exercises (already delivered). Exercise 1 :.

vivien
Download Presentation

Informatik I (D-ITET) Group 7, 15:00-17:00, ETZ H91 Assistant: Ercan Ucan

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Informatik I (D-ITET)Group 7, 15:00-17:00, ETZ H91Assistant: Ercan Ucan Slides at http://people.inf.ethz.ch/eucan/inf-1/ Exercise5 (29/10/2012)

  2. Discussion on Series 4 exercises (already delivered) • Exercise 1 : • charstr[1] = "z"; Correct. Wedont‘thavetoinitialize all thearrayelements. • int array[4] = {1,2}; Correct. Wedont‘thavetoinitialize all thearrayelements. • int a[3]; a = {1, 2, 3}; Not correct. The arraycanbeonlyinitialized via { } whenitisdeclared, not later on. • double matrix[][] = {{1.0, 2.0, 3.0}, {-5.0, 5.0}}; Not correct. Youareonlyallowedtoleave blank (andautomaticallyinitialized) thefirstdimensionof an array. • Possiblecorrection :double matrix[][3] = { { 1.0, 2.0, 3.0 }, { -5.0, 5.0 } }; • int a[5]; int b[5]; a = b; Not correct.

  3. Discussion on Series 4 exercises (already delivered) • Exercise 2 : void printPolynomial(double x, double c[], int n) { int degree; for(inti=0; i<n; i=i+1) { degree = n-i-1; if (i>0) cout << " + "; cout << c[i]; if (degree >= 1) { cout << "*" << x; if (degree > 1) cout << "^" << degree; } } } double evalPolynomial(double x, double c[], int n) { double result=0; double p = 1; for(inti=n-1; i>=0; i=i-1) { result = result + c[i]*p; p = p*x; } return result; } intderivePolynomial(double c[], int n) { //if the degree is zero, the polynomial gets reduced to a //constant of zero. if (n==1) { c[0] = 0; } else { //First, the degree is lowered n = n-1; //All coefficients are computed. for(int i=0; i<n; i=i+1) { c[i] = (n-i)*c[i]; } } //The new number of coefficients (degree+1) is returned. return n; }

  4. Discussion on Series 4 exercises (already delivered) • Exercise 2 : /* Main routine: - processes the programial arguments - prints the polynomial - evaluates the polynomial and prints the result @paramargc: number of arguments @paramargv: array of arguments as c-strings @return: error code (usually 0) */ int main(intargc, char* argv[]) { double x; int n; double coeffs[MAX_COEFFS]; if (argc < 3) { cout << "Please enter the value and at least 1 coefficent as command line arguments" << endl; return 0; } x = atof(argv[1]); n = argc-2; inti; for(i=0; i<n; i=i+1) coeffs[i]=atof(argv[i+2]); intnewN = n; //auxiliary variable do { n = newN; //assign the current number of //coefficients //print the polynomial printPolynomial(x, coeffs,n); //ealuate the polynomial and print the result; cout << " = " << evalPolynomial(x,coeffs,n)<< endl; //take the derivative of the polynomial and store the //new (degree-1) in newN newN = derivePolynomial(coeffs,n); } while(n>1); //iterate as long as the degree (=n-1) is //greater than zero return 0; }

  5. Discussion on Series 4 exercises (already delivered) • Exercise 3 (Using character arrays) : intmain (){ constintmaxLen = 100; char satz[maxLen]; char pass[maxLen]; //den Satz und das PasswortvomBenutzererfragen cout<< "GebenSieeinenSatzein:" << endl; cin.getline(satz, maxLen); cout<< "GebenSieeinPasswortein:" << endl; cin.getline(pass, maxLen); intsatz_laenge = strlen(satz); intpasswort_laenge = strlen(pass); char verschluesselt[maxLen]; // ENCRYPTION for (int i = 0; i < satz_laenge; i++) { int pass_char = (i % passwort_laenge); if (isalpha(satz[i])) { verschluesselt[i] = (((toupper(satz[i])-65) + (toupper(pass[pass_char])-65)) % 26) + 65; } else { verschluesselt[i] = satz[i]; } } //den c-String richtig abschliessen verschluesselt[satz_laenge] = '\0'; cout << "Verschluesselt: " << endl << verschluesselt << endl; cout << "Geben Sie ein Passwort ein:" << endl; cin.getline(pass, maxLen); passwort_laenge = strlen(pass); char entschluesselt[maxLen]; // DECRYPTION for (int i = 0; i < satz_laenge; i++) { int pass_char = (i % passwort_laenge); if (isalpha(verschluesselt[i])) { entschluesselt[i] = (((26 + (toupper(verschluesselt[i])-65)) - (toupper(pass[pass_char])-65)) % 26) + 65; } else { entschluesselt[i] = verschluesselt[i]; } } entschluesselt[satz_laenge] = '\0'; cout << "Entschluesselt: " << endl << entschluesselt << endl; return 0; }

  6. Sorting Algorithms - Introduction to Algorithms • General problem posing: • Input: An array of n integers • Output: An array of the same size, where the n elements are sorted in ascending order. Mathematically, we are looking for a permutation(reordering)

  7. Sorting Algorithms - Bubble Sort • How it works: It repeatedly steps through the list to be sorted, comparing each pair of adjacent items and swapping them if they are in the wrong order. The pass through the list is repeated until no swaps are needed, which indicates that the list is sorted. The algorithm gets its name from the way smaller elements "bubble" to the top of the list.

  8. Sorting Algorithms - Bubble Sort – Complexity Analysis Pseudo-code (from Wikipedia): bubbleSort( array A ) repeat swapped = false for i = 1 to length(A) - 1 do: if A[i-1] > A[i] then swap( A[i-1], A[i] ) swapped = true end if end for until not swapped end procedure Complexity Analysis (here): How many times there is a new assignment of an array-element (red in the pseudo-code) Best case scenario: Array A in sorted order Average case scenario: Between best and worst • The bubble sort algorithm can be easily optimized by observing that the n-th pass finds the n-th largest element and puts it into its final place. So, the inner loop can avoid looking at the last n-1 items when running for the n-th time Worst case scenario: Array A in reverse sorted order

  9. STRUCTS (structures) • A group of data elements grouped together under a common name. • The data elements can be of different type and length. • structstructureName { • memberType1 memberName1; • memberType1 memberName1; • . • . • } ; • For example: • struct product { • int weight; • float price; • }; • product apple, banana; • apple.weight = 2; • apple.price = 5.2; Once declared, product has become a valid data type, so we can declare objects(variables) of this new compound type. You can refer to the individual elements using the dot operator

  10. STRUCTS (structures) • Let’s say that you want to create a database with ETHZ students. • struct student { string name; short int age; char gender; // must be 'm' or 'w' char legi[11];}; • Then the ETHZ student database can be a large array where each element is such a structure: • student ethz_students[15000]; • We can start filling the database either element wise, e.g. • eth_students[0].name = “ErcanUcan”; • eth_students[0].age = 18;  • Or initializing the whole structure at once, e.g. • eth_students[0] = {“ErcanUcan”, 18, 'm', “09-901-027"};

  11. STRUCTS (structures) • You can also build structures that contain other structures, e.g. • struct department { string depName; student depStudents[1000]; }; • Structures are passed “by value” as function arguments • Assignment here works (for structures of the same type) e.g. • struct value { • double x; • char name[10]; • } a = { 5.6, "start" }; • value b; // structure b of same type • b.x = a.x // legal - copy doubles • b.name = a.name; // illegal - not allowed for arrays • But: b = a // Valid – Also copies the array elements.

  12. ENUM (enumerations) • Another way to create symbolic constants. Allows for defining new types in a fairly restricted fashion. • enumenumerationName { • value1, • value2, • . • . • } objectNames; • For example: • enum spectrum {red, orange, yellow, green, blue, violet, ultraviolet};

  13. ENUM (enumerations) • Another way to create symbolic constants. Allows for defining new types in a fairly restricted fashion. • enumenumerationName { • value1, • value2, • . • . • } objectNames; • For example: • enum spectrum {red, orange, yellow, green, blue, violet, ultraviolet}; • This statement does two things: • Makes spectrum the name of a new data type. • Establishes red, orange, yellow etc. as symbolic constants for the integer values 0-6. These constants are called enumerators. • The only values you can assign to an enumerator variable are the enumerator values used in defining this specific type.

  14. ENUM (enumerations) • Only the assignment operator is defined for enumerators. • Also enums can be promoted to int but not the other way around. • spectrum band; \\Valid – Declaration • band = red; • ++band; \\Not Valid • band = 3; \\Not Valid – int is not converted to spectrum • int color = blue; color = 3 + red; \\Valid – red converted to int • And something tricky-funny: • band = orange + red; is not valid. Why? • So, we said that arithmetic operators are not defined for enumerators. We also said that enumerators are internally converted to integers, which should convert the above to 1+0 which is a valid expression. But the result then is of type int which then cannot be converted to spectrum and assigned to band.

  15. Exercise 1 – Bubble Sort • We already described how sorting with bubble sort works. • You are asked to write a c++ program that implements the algorithm. More specifically: • Implement a functionvoid sortierenDurchAufsteigen(int liste[], int length) which takes as input an int array of a given lenth and sorts it using the insertion algorithm (Remember that arrays are passed by reference into the function). • Then, output the sorted array.

  16. Exercise 2 – Compare Sorting Algorithms You have to compare bubble sort and selection sorting algorithms in the following cases: Examine the two sorting algorithms separately: Does the initial arrangement of the array influence the number of steps? If so, specify such a configuration that results in least and most favorable. Given is an array with N elements. What is the minimum and maximum number of comparisons between array elements? Consider again the two algorithms. This can be based on the results from part a). Besides comparisons, which operation is crucial of the efficiency of a sorting algorithm? How do the two algorithms behave w.r.t this operation? Pseudo-code (from Wikipedia): bubbleSort( array A ) repeat swapped = false for i = 1 to N-1 do: if A[i-1] > A[i] then swap( A[i-1], A[i] ) swapped = true end if end for until not swapped end procedure

  17. Exercise 3 – Structs • Write a program that parses a text into its components – vowels, consonants, numbers, spaces and special characters (, - .) • Character types are defined inside an enumerator zeichenart • {vokal = 0, konsonant = 1, ziffer = 2, leerzeichen = 3, sonderzeichen = 4} • The given framework already reads the text file ETH.txt and stores it into a string. • Create a structsatz. This struct represents a sentence (as a string) and the number of vowels, consonants etc. contained in this sentence. • Write a function zeichenartzeichenart_von_character(char c) which takes a character and returns its type. • Write a function satzsatz_aus_string(string einSatz) which takes a sentence as input and returns the structure with the statistics. • Write a main function that generates global statistics for the whole ETH.txt file.

  18. Exercise 3 – Structs

More Related